2

How can I pass a non-serializable object over a network?

4
  • 6
    You can't - you'll have to think about your problem, and think about which informations you really want to pass. (there are things you should never attempt to serialize, such as Thread) Commented Feb 7, 2011 at 13:27
  • 1
    What is the reason the object is not serializable? Commented Feb 7, 2011 at 13:33
  • code.google.com/p/protobuf Commented Feb 7, 2011 at 13:33
  • @Jean: Of course you can. You just can't use java.io serialization to do it. Commented Feb 7, 2011 at 13:54

2 Answers 2

2

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.

  1. 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.
  2. 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
  3. Subclass your given class. Mark subclass as Seriablizable. Implement your own writeObject() and readObject() methods.
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Nitpick: java.io.Serializable is an interface, not a keyword.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.