There is, however, a strange yet crafty solution. By using a built-in feature of the serialization mechanism, developers can enhance the normal process by providing two methods inside their class files. Those methods are:
private void writeObject(ObjectOutputStream out) throws IOException;
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;
Notice that both methods are (and must be) declared
private, proving that neither method is inherited and overridden or overloaded. The trick here is that the virtual machine will automatically check to see if either method is declared during the corresponding method call. The virtual machine can call private methods of your class whenever it wants but no other objects can. Thus, the integrity of the class is maintained and the serialization protocol can continue to work as normal. The serialization protocol is always used the same way, by calling either
ObjectInputStream.readObject(). So, even though those specialized private methods are provided, the object serialization works the same way as far as any calling object is concerned.
readResolve is called after
readObject has returned (conversely
writeReplace is called before
writeObject and probably on a different object). The object the method returns replaces
this object returned to the user of
ObjectInputStream.readObject and any further back references to the object in the stream. It is mostly used for serial proxies for example in case is Singleton class if it is serializable then we need to specify in readResolve that it returns singleton object and not the one which is read from persisted location.