CONTENTS | PREV | NEXT | Java Object Serialization Specification |
TheReplaceable
interface allows an object to nominate its own replacement in the stream before the object is written. TheResolvable
interface allows a class to replace/resolve the object read from the stream before it is returned to the caller. The interfaces are defined as:package java.io; public interface Replaceable extends Serializable { public Object writeReplace(Object obj); } public interface Resolvable extends Serializable { public Object readResolve(Object obj); }By implementing theReplaceable
interface the class itself can directly control the types and instances of its own instances being serialized. By implementing theResolvable
interface the class itself can directly control the types and instances of its own instances being deserializedFor example, a
Symbol
class could be created for which only a single instance of each symbol binding existed within a virtual machine. ThereadResolve
method would be implemented to determine if that symbol was already defined and substitute the preexisting equivalent
Symbol
object to maintain the identity constraint. In this way the uniqueness ofSymbol
objects can be maintained across serialization.TheThewriteReplace
method is called whenObjectOutputStream
is preparing to write the object to the stream. TheObjectOutputStream
checks to see if the class implements theReplaceable
interface. If so, it calls thewriteReplace
method to allow the object to designate its replacement in the stream. The object returned either should be of the same type as the object passed in or an object that when read and resolved will result in an object of a type that is compatible with all references to the object, otherwise aClassCastException
will occur when the type mismatch is discovered.readResolve
method is called whenObjectInputStream
has read an object from the stream and is preparing to return it to the caller.ObjectInputStream
checks if the object implements theResolvable
interface. If so, it calls thereadResolve
method to allow the object in the stream to designate the object to be returned. The object returned should be of a type that is compatible with all uses or aClassCastException
will be thrown when the type mismatch is discovered.