Java / Object, Class and Package
Difference between readObject and readResolve in Java serialization.
The readObject method is responsible for reading from the stream and restoring the classes fields.
readResolve is used for replacing the object read from the stream. This helps enforcing singletons; when an object is read, replace it with the singleton instance. This ensures that nobody can create another instance by serializing and deserializing the singleton.
The readResolve method is called when ObjectInputStream has read an object from the stream and is preparing to return it to the caller. ObjectInputStream checks whether the class of the object defines the readResolve method. If the method is defined, the readResolve method is called to allow the object in the stream to designate the object to be returned.
More Related questions...