спецификации, руководства, описания, API
|CONTENTS | PREV | NEXT||Java Object Serialization Specification|
For Serializable and Externalizable classes, the
readResolvemethod allows a class to replace/resolve the object read from the stream before it is returned to the caller. By implementing the
readResolvemethod, a class can directly control the types and instances of its own instances being deserialized. The method is defined as follows:
ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;The
readResolvemethod is called when
ObjectInputStreamhas read an object from the stream and is preparing to return it to the caller.
ObjectInputStreamchecks whether the class of the object defines the
readResolvemethod. If the method is defined, the
readResolvemethod is called 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. If it is not compatible, a ClassCastException will be thrown when the type mismatch is discovered.
For example, a
Symbolclass could be created for which only a single instance of each symbol binding existed within a virtual machine. The
method would be implemented to determine if that symbol was already defined and substitute the preexisting equivalent
Symbolobject to maintain the identity constraint. In this way the uniqueness of
Symbolobjects can be maintained across serialization.
Note - The
readResolvemethod is not invoked on the object until the object is fully constructed, so any references to this object in its object graph will not be updated to the new object nominated by
readResolve. However, during the serialization of an object with the
writeReplacemethod, all references to the original object in the replacement object's object graph are replaced with references to the replacement object. Therefore in cases where an object being serialized nominates a replacement object whose object graph has a reference to the original object, deserialization will result in an incorrect graph of objects. Furthermore, if the reference types of the object being read (nominated by
writeReplace) and the original object are not compatible, the construction of the object graph will raise a ClassCastException.