Java in a Nutshell

Previous Chapter 9
Object Serialization
Next
 

9.3 Serialization and Class Versioning

When an object is serialized, some information about its 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. 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 of a class is stored in a constant long field named serialVersionUID. For example, a class might declare its version number with a field like this:

static final long serialVersionUID = 280432937854755317L;

If a class does not define a serialVersionUID constant, the ObjectOutputStream automatically computes a unique version number for it by applying the Secure Hash Algorithm (SHA) to the name of the class, its interfaces, fields, and methods. In this case, any change to a field in a class or to a non-private class method signature results in a change to the automatically-computed unique version number.

If you need to make minor changes to a class without breaking serialization compatibility, you should explicitly declare a serialVersionUID constant so that an updated and incompatible version number is not automatically generated. You can use the serialver program that is provided with the JDK to compute an initial value for this constant for the first version of your class. When you make minor, compatible changes to the class, leave the constant unchanged. Then, if you make larger changes that break serialization compatibility, run serialver again to generate an updated version number.


Previous Home Next
Custom Serialization Book Index Serialized Applets

Java in a Nutshell Java Language Reference Java AWT Java Fundamental Classes Exploring Java
This HTML Help has been published using the chm2web software.