Martin08
Martin08

Reputation: 21450

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.

Upvotes: 49

Views: 40932

Answers (5)

Daniel Jipa
Daniel Jipa

Reputation: 888

You can use Kryo. It works on non serialized classes but classes needs registered aforehand.

Upvotes: 1

C. K. Young
C. K. Young

Reputation: 223023

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. :-)

Upvotes: 47

rox
rox

Reputation: 49

If your class already implements the Serializable interface (required for serializing), all you must do is to declare the field you don't want to serialize with transient:

    public transient String description;

Upvotes: 0

Steve Emmerson
Steve Emmerson

Reputation: 7832

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. :-)

Upvotes: 7

Michael McGowan
Michael McGowan

Reputation: 6608

If the class is not final, you can make your own class that extends it and implements Serializable. There are lots of other ways to serialize besides Java's built-in mechanism though.

Upvotes: -5

Related Questions