There is a class I want to serialize, and it implements Serializable, but one of the objects it contains does not implement Serializable.
Is there a way to modify the class at runtime to make it implement the Serializable interface so I can serialize it? I can't change it at compile time because its a third party library.
Maybe I would have to use some sort of bytecode writer or something?
EDIT: Both the containing class and contained class are in the 3rd party library so I don't think i can mark something as transient. The containing class is marked as serializable, but it contains an object that is not.
I'm fine with writing a custom serialization method for the class, not sure how I would do this though, would I have to use reflection to get the values of the private variables?
If the superclass is Serializable, then by default, every subclass is serializable. Hence, even though subclass doesn't implement Serializable interface( and if its superclass implements Serializable), then we can serialize subclass object.
If our class does not implement Serializable interface, or if it is having a reference to a non- Serializable class, then the JVM will throw NotSerializableException . All transient and static fields do not get serialized.
The Student would not be Serializable, and it will act like a normal class. Serialization is the conversion of an object to a series of bytes, so that the object can be easily saved to persistent storage or streamed across a communication link.
It'll throw a NotSerializableException when you try to Serialize it.
Reading the javadoc for Serializable, I see:
Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:
private void writeObject(java.io.ObjectOutputStream out)
throws IOException
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;
private void readObjectNoData()
throws ObjectStreamException;
which you could use to manually serialize the uncooperative fields. You could look into using ASM, but it seems hard to believe that it is a maintainable solution.
Fields can be skipped using the transient
modifier. Additional data can be added to the stream by providing readObject
and writeObject
methods. Classes can be subclassed to make them serialisable (though you will need to manage the superclass data), or use a serial proxy (see Effective Java).
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