I am reading some materials on Java serialization and found that, for self defined type, we can define two member functions in the type to change the default serializing behavior:
private void readObject(java.io.ObjectInputStream in)
private void writeObject(java.io.ObjectOutputStream out)
I have two questions about this:
1. These two functions are all qualified with private keyword, how are they called during the serializing process?
2. We all know that Java Serializable Interface is an empty interface, so how does the serializing mechanism knows to call these two function to serialize and deserialize?
Looking forward to you help!
cheng
Java serialization involves magic in the JVM, basically. Heck, it can involve creating an object without calling a constructor, even.
It’s easy to tell (from suitably trusted code) whether a class provides certain methods, via reflection. The serialization framework code is sufficiently trusted to determine that as well as invoking the methods.
Just detecting and invoking a private method from another class is feasible (again, with suitably trusted code) in normal Java of course: