I am trying to write message to a file using serialization.Message consists of two fields-
date and TibrvMsg
(TibrvMsg
is a p开发者_Go百科ropriotory message by Tibco and this class is not serializable as per their documentation).So my custom message is:
Message msg = new Message(TibrvMsg msg)
Problem is though i am declaring Message Serializable
, i am not able to serialize it as TibrvMsg
is not serializable.
So i get java.io.NotSerializableException: com.tibco.tibrv.TibrvMsg
exception.
Another approach is to use a serialization proxy. Serialization proxy is a different class altogether than the object being serialized with the logical state of the object. The Object readResolve() method to write a proxy instead of this object and create an object by reading proxy.
Some semi-pseudo code:
class Message implements Serializable {
private Date dt;
private TibrvMsg msg;
private Object writeReplace() {
return new Proxy(this);
}
private static class Proxy implements Serializable {
private Date dt;
private Map msgData;
Proxy(Message msg) {
this.dt = msg.dt;
this.msgData = doTransform(msg.msg, "UTF-16");
}
private Object readResolve() {
Message msg = new Message();
msg.dtd = dt;
msg.msg = asTibrvMsg(msgData);
return msg;
}
}
}
Additionally override readObject(ObjectInputStream) to throw an InvalidObjectException. The serialization proxy pattern also has certain security advantages over normal serialization. It also has a few disadvantages
You need to find a way to represent your TibrvMsg as a serializable object (maybe something like this, which transforms it into a Map).
You can then override the following two methods to write this data to the output stream (or read it):
private void writeObject(java.io.ObjectOutputStream out)
throws IOException{
out.writeObject(date);
out.writeObject(doSomethingWithTibrv(tibrv);
}
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException{
date = (Date) in.readObject();
tibrv = readTibrv(in.readObject());
}
What do you mean by "this class is not serializable as per their documentation"? Couldent you just extend their class and implement serializable? Its just a marker interface, so...
精彩评论