CONTENTS | PREV | NEXT Java Object Serialization Specification


1.12 The Replaceable & Resolvable Interfaces

The Replaceable interface allows an object to nominate its own replacement in the stream before the object is written. The Resolvable 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 the Replaceable interface the class itself can directly control the types and instances of its own instances being serialized. By implementing the Resolvable interface the class itself can directly control the types and instances of its own instances being deserialized

For example, a Symbol class could be created for which only a single instance of each symbol binding existed within a virtual machine. The readResolve 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 of Symbol objects can be maintained across serialization.

The writeReplace method is called when ObjectOutputStream is preparing to 
write the object to the stream. The ObjectOutputStream checks to see if the class 
implements the Replaceable interface. If so, it calls the writeReplace 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 a ClassCastException will occur when the type mismatch is 
discovered.
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 if the object implements the Resolvable interface. If so, it calls the readResolve 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 a ClassCastException will be thrown when the type mismatch is discovered.



CONTENTS | PREV | NEXT
Copyright © 1997-1998 Sun Microsystems, Inc. All Rights Reserved.