Reputation: 5419
Is this really the way to receive POJOs with JMS?
public void onMessage(Message msg) {
ObjectMessage objMsg = (ObjectMessage) msg;
if(objMsg.getObject() instanceof <<sometype>>) {
//do something
}
}
Do I have to cast to ObjectMessage. Actually then i have to check if msg is castable to ObjectMessage too.
or do i miss something?
thx
Upvotes: 4
Views: 9764
Reputation: 22279
Yes, and you might want to check some exceptions. However with spring (and Frameworks such as apache camel) you could rather easily wire up a bean that simply processes objects of some class. That might or might not be worth the overhead and added complexity of configuration to simplify the code.
Look a few pages into this article for a description: http://www.wmrichards.com/mdp.pdf
Upvotes: 1
Reputation: 692121
AFAIK, that's it. It's pretty rare to mix different message types, and different object types inside the message, in a single destination (queue or topic), though. So you might skip the instanceof checks if you know that only ObjectMessages containing SomeType objects are expected.
Upvotes: 1
Reputation: 103567
Quoting example from JMS Spring Doc, as you can see from example, we need to check if message is of TextMessage type or not and so similarly in your case we have to check for casting or check for whether your object is instance of message type, so you have two approaches for it, hope this clarifies your issue.
Example
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
public class ExampleListener implements MessageListener {
public void onMessage(Message message) {
if (message instanceof TextMessage) {
try {
System.out.println(((TextMessage) message).getText());
}
catch (JMSException ex) {
throw new RuntimeException(ex);
}
}
else {
throw new IllegalArgumentException("Message must be of type TextMessage");
}
}
}
Upvotes: 1