具有这样的自定义对象:
package Messages;
import java.io.Serializable;
import javax.jms.TextMessage;
public class MessageObject implements Serializable{
private static final long serialVersionUID = 1L;
private TextMessage message;
private String state;
private String sender;
private String receiver;
public MessageObject() {
}
public TextMessage getMessage() {
return message;
}
public void setMessage(TextMessage message) {
this.message = message;
}
* the rest of the getters and setters *
}
然后我创建我尝试将包含我的自定义消息对象的ObjectMessage发送到jms队列:
try {
Context context = new InitialContext();
QueueConnectionFactory factory =
(QueueConnectionFactory)context.lookup("tiwconnectionfactory");
Queue queue = (Queue) context.lookup("tiwqueue");
Connection connection = factory.createConnection();
connection.start();
Session session= connection.createSession(false,
javax.jms.Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(queue);
MessageObject mymessage = new MessageObject();
ObjectMessage object = session.createObjectMessage();
TextMessage message = session.createTextMessage();
message.setText("Hi");
mymessage.setState("still not read");
mymessage.setMessage(message);
mymessage.setSender("Peter");
mymessage.setReceiver("John");
object.setObject(mymessage);
producer.send(object);
尝试运行代码时,抛出的异常是:
[2018-11-11T19:20:07.270+0100] [glassfish 5.0] [SEVERE] [] [] [tid: _ThreadID=28 _ThreadName=Thread-9] [timeMillis: 1541960407270] [levelValue: 1000] [[ javax.jms.JMSException:MQJMSRA_DM4001::Exception:ObjectMessage.setObject()object=Messages.MessageObject@d8b66e3:message=com.sun.messaging.jms.ra.DirectTextPacktatcom.sun.messaging.jms.ra.DirectObjectPacket.setObject(DirectObjectPacket.java:218)
那么问题是什么?我在代码中找不到任何错误,并且我的对象可序列化。
答案 0 :(得分:1)
我用google找出了您的错误消息:
[2018-11-11T19:20:07.270+0100] [glassfish 5.0] [SEVERE] [] [] [tid: _ThreadID=28 _ThreadName=Thread-9] [timeMillis: 1541960407270] [levelValue: 1000]
[[ javax.jms.JMSException:MQJMSRA_DM4001::Exception:ObjectMessage.setObject()
object=Messages.MessageObject@d8b66e3:
message=com.sun.messaging.jms.ra.DirectTextPacket
at com.sun.messaging.jms.ra.DirectObjectPacket.setObject(DirectObjectPacket.java:218)
似乎TextMessage
对象实际上是com.sun.messaging.jms.ra.DirectTextPacket
的实例。
但是,要使您的MessageObject
可序列化,其所有字段也必须可序列化。由于DirectTextPacket
不可序列化,因此您的MessageObject
不可序列化。
要回答“为什么要获得此异常而不是NotSerializableException
”这个问题?
这是因为JMS将NotSerializableException
之类的异常包装为自己的异常。
我不明白的是:为什么要让您的MessageObject
包含包装好的TextMessage
?为什么不将文本本身添加到您的MessageObject
中?