Versioning

When an object is written onto a stream, only the state of the object and the name of the object’s class are stored; the byte codes for the object’s class are not stored with the object. There’s no guarantee that a serialized object will be deserialized into the same environment from which it was serialized. It’s possible for the class definition to change between the time the object is written and the time it’s read. For instance, a Component object may be written in Java 1.1 but read in Java 2. However, in Java 2 the Component class has three nonstatic, nontransient fields the 1.1 version of Component does not:

boolean inputMethodsEnabled;
DropTarget dropTarget;
private PropertyChangeSupport changeSupport;

There are even more differences when methods, constructors, and static and transient fields are considered. Not all changes, however, prevent deserialization. For instance, the values of static fields aren’t saved when an object is serialized. Therefore, you don’t have to worry about adding or deleting a static field to or from a class. Similarly, serialization completely ignores the methods in a class, so changing method bodies or adding or removing methods does not affect serialization. However, removing an instance field does affect serialization, because deserializing an object saved by the earlier version of the class will result in an attempt to set the value of a field that no longer exists.

Compatible and Incompatible Changes

Changes to a class are divided into ...

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.