| CONTENTS | PREV | NEXT | Java Object Serialization Specification |
For Serializable and Externalizable classes, thewriteReplacemethod allows a class of an object to nominate its own replacement in the stream before the object is written. By implementing thewriteReplacemethod, 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;ThewriteReplacemethod is called whenObjectOutputStreamis preparing to write the object to the stream. TheObjectOutputStreamchecks whether the class defines thewriteReplacemethod. If the method is defined, thewriteReplacemethod 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, a ClassCastException will occur when the type mismatch is discovered.