I have a code that gets a message from a JMS queue, but I don't understand how to get the body of the message if it is a byte and translate it into a String
:
connectQueueBrowser();
Enumeration<Message> messageEnumeration = queueBrowser.getEnumeration();
ArrayList<Message> messages = new ArrayList<>();
while (messageEnumeration.hasMoreElements()){
messages.add(messageEnumeration.nextElement());
}
System.out.println(messages.get(0).getBody(String.class));
This is the error I get:
javax.jms.MessageFormatException: Body not assignable to class java.lang.String
But I get an error when I display body messages.
If you have sent a JMS BytesMessage
then you can only use getBody
with byte[].class
, e.g.:
System.out.println(messages.get(0).getBody(byte[].class));
If you've serialized a Java String
into the BytesMessage
using something like this:
bytesMessage.writeBytes(myString.getBytes(StandardCharsets.UTF_8));
Then you'll be able to deserialize that String
from the BytesMessage
using something like this:
byte[] myBytes = new byte[(int)bytesMessage.getBodyLength()];
bytesMessage.readBytes(myBytes);
String myString = new String(myBytes, StandardCharsets.UTF_8);