Customizing the Serialization Format

The default serialization procedure does not always produce the results you want. Most often, a nonserializable field like a Socket or a FileOutputStream needs to be excluded from serialization. Sometimes, a class may contain data in nonserializable fields like a Socket that you nonetheless want to save—for example, the host that the socket’s connected to. Or perhaps a singleton object wants to verify that no other instance of itself exists in the virtual machine before it’s reconstructed.[19] Or perhaps an incompatible change to a class (such as changing a Font field to three separate fields storing the font’s name, style, and size) can be made compatible with a little programmer-supplied logic. Or perhaps you want an exceptionally large array of image data to be compressed before being written to disk. For these or many other reasons, you’re allowed to customize the serialization process.

The simplest way to customize serialization is to declare certain fields transient. The values of transient fields will not be written onto the underlying output stream when an object in the class is serialized. However, this only goes as far as excluding certain information from serialization; it doesn’t help you change the format that’s used to store the data or take action on deserialization or ensure that no more than one instance of a singleton class is created.

For more control over the details of your class’s serialization, you can provide custom readObject() ...

Get Java I/O 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.