CONTENTS | PREV | NEXT | Java Object Serialization Specification |
For Serializable and Externalizable classes, thewriteReplace
method allows a class of an object to nominate its own replacement in the stream before the object is written. By implementing thewriteReplace
method, a class can directly control the types and instances of its own instances being serialized.The method is defined as follows:
ANY-ACCESS-MODIFIER Object writeReplace() { throws ObjectStreamException;The
writeReplace
method is called whenObjectOutputStream
is preparing to write the object to the stream. TheObjectOutputStream
checks whether the class defines thewriteReplace
method. If the method is defined, thewriteReplace
method is called to allow the object to designate its replacement in the stream. The object returned should be either 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. If it is not, aClassCastException
will occur when the type mismatch is discovered.