jsr343-experts@jms-spec.java.net

[jsr343-experts] (JMS_SPEC-101) New method Message.getPayload(Class<T> c)

From: Nigel Deakin <nigel.deakin_at_oracle.com>
Date: Tue, 23 Oct 2012 12:29:43 +0100

Following Pete's proposal (and Chris's support) I have logged this JIRA issue:

http://java.net/jira/browse/JMS_SPEC-101
New method Message.getPayload(Class<T> c)

Please indicate whether you support adding this new method to JMS 2.0.

This is a proposal to add a new method to javax.jms.Message which allows the message payload to be obtained without the
need to cast the object to the appropriate subtype first. This can slightly simplify the code of a MessageListener's,
onMessage method, where the object passed in is always declared to be a javax.jms.Message.

Here is the proposed API:

        /**
         * Returns the messages's payload, which must be of the specified type. If
         * the message has no payload then null is returned. This method may be used
         * to obtain the payload of any type of message except for
         * <tt>StreamMessage</tt>.
         * * @param c
         * The class of the payload.<br/>
         * If the message is a <code>TextMessage</code> then this should
         * be set to <code>String.class</code>.<br/>
         * If the message is a <code>ObjectMessage</code> then this
         * should be set to <code>java.io.Serializable.class</code>. <br/>
         * If the message is a <code>MapMessage</code> then this should
         * be set to <code>java.util.Map.class</code>.<br/>
         * If the message is a <code>BytesMessage</code> then this should
         * be set to <code>byte[].class</code>.<br/>
         * If the message payload is not of the specified type a
         * <code>MessageFormatException</code> will be thrown
         * * @return the messages's payload
         * * @exception JMSException
         * if the JMS provider fails to get the payload due to some
         * internal error.
         * @exception MessageFormatException
         * if the payload is not of the specified type or, if the
         * message is an ObjectMessage, if object deserialization
         * fails.
         * @Exception MessageNotReadableException - if the message is a BytesMessage
         * and the message is in write-only mode.
         */
        <T> T getPayload(Class<T> c) throws JMSException;

This means that instead of something like:

     public void onMessage(Message message) {
         String payload = ((TextMessage) message).getText();

we could have

     public void onMessage(Message message) {
         String payload2 = message.getPayload(String.class);