Customizing Object Serialization

Sometimes it is useful, or even necessary, to control how an individual object is serialized. If for instance you want to encrypt the data values held by the object's attributes, you would not want to use the default serialization mechanisms.

To override how an object is serialized or deserialized, you must implement two methods in your class with these exact signatures:

private void writeObject(java.io.ObjectOutputStream out)
     throws IOException
 private void readObject(java.io.ObjectInputStream in)
     throws IOException, ClassNotFoundException;

You might have noticed that the Serializable interface does not define any methods. If you look back at the Employee class from listing 22.4, no methods had to be implemented ...

Get Special Edition Using Java 2 Standard Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.