The Java EE 5 Tutorial

Message Bodies

The JMS API defines five message body formats, also called message types, which allow you to send and to receive data in many different forms and provide compatibility with existing messaging formats. Table 31–2 describes these message types.

Table 31–2 JMS Message Types

Message Type 

Body Contains 


A java.lang.String object (for example, the contents of an XML file).


A set of name-value pairs, with names as String objects and values as primitive types in the Java programming language. The entries can be accessed sequentially by enumerator or randomly by name. The order of the entries is undefined.


A stream of uninterpreted bytes. This message type is for literally encoding a body to match an existing message format. 


A stream of primitive values in the Java programming language, filled and read sequentially. 


A Serializable object in the Java programming language.


Nothing. Composed of header fields and properties only. This message type is useful when a message body is not required. 

The JMS API provides methods for creating messages of each type and for filling in their contents. For example, to create and send a TextMessage, you might use the following statements:

TextMessage message = session.createTextMessage();
message.setText(msg_text);     // msg_text is a String

At the consuming end, a message arrives as a generic Message object and must be cast to the appropriate message type. You can use one or more getter methods to extract the message contents. The following code fragment uses the getText method:

Message m = consumer.receive();
if (m instanceof TextMessage) {
    TextMessage message = (TextMessage) m;
    System.out.println("Reading message: " + message.getText());
} else {
    // Handle error