Java Reference
In-Depth Information
20.8.5. Object Versioning
Class implementations change over time. If a class's implementation
changes between the time an object is serialized and the time it is
deserialized, the
ObjectInputStream
can detect this change. When the ob-
ject is written, the
serial version
UID
(unique identifier), a 64-bit
long
value, is written with it. By default, this identifier is a secure hash of the
full class name, superinterfaces, and membersthe facts about the class
that, if they change, signal a possible class incompatibility. Such a hash
is essentially a fingerprintit is nearly impossible for two different classes
to have the same
UID
.
When an object is read from an
ObjectInputStream
, the serial version
UID
is also read. An attempt is then made to load the class. If no class with
the same name is found or if the loaded class's
UID
does not match the
UID
in the stream,
readObject
throws an
InvalidClassException
. If the ver-
sions of all the classes in the object's type are found and all the
UID
s
match, the object can be deserialized.
This assumption is very conservative: Any change in the class creates
an incompatible version. Many class changes are less drastic than this.
Adding a cache to a class can be made compatible with earlier versions
of the serialized form, as can adding optional behavior or values. Rath-
er then relying on the default serial version
UID
, any serializable class
should explicitly declare its own serial version
UID
value. Then when you
make a change to a class that can be compatible with the serialized
forms of earlier versions of the class, you can explicitly declare the serial
version
UID
for the earlier class. A serial version
UID
is declared as fol-
lows:
private static final
long serialVersionUID = -1307795172754062330L;
The
serialVersionUID
field must be a static, final field of type
long
. It
should also be private since it is only applied to the declaring class. The
value of
serialVersionUID
is provided by your development system. In