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.
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.)
No. If you want to serialise an object it must implement the tagging Serializable interface.
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 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.
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.
transient
.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.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. :-)
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. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With