Customizing Serialization

Most of the time, you will probably be happy with the default serialization mechanism. Sometimes, however, you might need to change the way an object writes itself to a stream and reads itself from a stream.

To create a custom serialization routine for your object, create your own implementations of writeObject and readObject. The writeObject method is declared as the following:

private void writeObject(ObjectOutputStream out)
    throws IOException

Note

The writeObject and readObject methods are somewhat peculiar because the method signature must be exact. You can't change the access modifier—it must be private. The serialization API only recognizes these methods if they exactly match the documented specification.

Get Special Edition Using Java™ 2 Enterprise 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.