Problem with serializability
How can I pass a non-serializable ob开发者_开发知识库ject over a network?
If there is a serious reason that the object is not serializable you cannot pass it over network. For example if your class contains members that cannot be serialized (streams, threads etc.)
But if the reason that the class is not serializable is that its author just did not mark it this way and you do not have access to class' source code to make it serializable you have the following ways.
- Use byte code engineering library to modify the class byte code on the fly: mark it as
implements Serializable
and then send it over network. - Write your own serialization mechanism. It can be completely custom created or use third party libraries. If you are implementing such mechanism yourself you can use reflection API. One of very good third party libraries is XStream. As far as I remember it does not require that class is marked as serializable. It just create XML that contains whole object graph. Custom mechanism may be also implemented using java.io.Externalizable
- Subclass your given class. Mark subclass as Seriablizable. Implement your own writeObject() and readObject() methods.
Use a library like XStream. XStream in particular will turn your code into xml which can then be sent across the network and reconstituted on the other side. There are many alternatives to the Serialization mechanism built into Java and most do not require the Serializable interface.
精彩评论