Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize a non-serializable in Java?

How can I serialize an object that does not implement Serializable? I cannot mark it Serializable because the class is from a 3rd party library.

like image 863
Martin08 Avatar asked May 28 '11 19:05

Martin08


People also ask

Can serializable class contain non-serializable field in Java?

the non-serializable field's Class must have an API to allow getting it's state (for writing to the object stream) and then instantiating a new instance with that state (when later reading from the object stream.)

Can we serialize an object without implementing serializable interface?

No. If you want to serialise an object it must implement the tagging Serializable interface.

How do you make a class non-serializable in Java?

There is no direct way to prevent sub-class from serialization in java. One possible way by which a programmer can achieve this is by implementing the writeObject() and readObject() methods in the subclass and needs to throw NotSerializableException from these methods.

What happens if object is not serializable?

What happens if you try to send non-serialized Object over network? When traversing a graph, an object may be encountered that does not support the Serializable interface. In this case the NotSerializableException will be thrown and will identify the class of the non-serializable object.


2 Answers

You can't serialise a class that doesn't implement Serializable, but you can wrap it in a class that does. To do this, you should implement readObject and writeObject on your wrapper class so you can serialise its objects in a custom way.

  • First, make your non-serialisable field transient.
  • In writeObject, first call defaultWriteObject on the stream to store all the non-transient fields, then call other methods to serialise the individual properties of your non-serialisable object.
  • In readObject, first call defaultReadObject on the stream to read back all the non-transient fields, then call other methods (corresponding to the ones you added to writeObject) to deserialise your non-serialisable object.

I hope this makes sense. :-)

like image 155
Chris Jester-Young Avatar answered Sep 18 '22 19:09

Chris Jester-Young


Wrap the non-serializable class in a class of your own that implements Serializable. In your class's writeObject method, do whatever's necessary to serialize sufficient information on the non-serializable object so that your class's readObject method can reconstruct it.

Alternatively, contact the developer of the non-serializable class and tell him to fix it. :-)

like image 37
Steve Emmerson Avatar answered Sep 17 '22 19:09

Steve Emmerson