Serialization and Class Versioning

One of the features of Example 10-3 is that it includes a version number in the serialization stream it writes. This is useful if the class evolves in the future and needs to use a new serialization format. The version number allows future versions of the class to recognize serialized objects written by this version of the class.

For Serializable objects that are not Externalizable, the Serialization API handles versioning itself. When an object is serialized, some information about the object’s class must obviously be serialized with it, so that the correct class file can be loaded when the object is deserialized. This information about the class is represented by the java.io.ObjectStreamClass class. It contains the fully qualified name of the class and a version number for the class. The version number is very important because an early version of a class may not be able to deserialize a serialized instance created by a later version of the same class. The version number for a class is a long value. By default, the serialization mechanism creates a unique version number by computing a hash of the name of the class, the name of its superclass and any interfaces it implements, the name and type of its fields, and the name and type of its nonprivate methods. Thus, whenever you add a new method, change the name of a field, or make even minor modifications to the API or implementation of a class, its computed version number changes. When an object ...

Get Java Examples in a Nutshell, 3rd 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.