In java, is it possible to add the Serializable interface to class that doesn't have it at runtime?
java, serialization
Solution
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.
Problem
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?