Java Reference
In-Depth Information
Everyserializedobjecthasanidentifier.Thedeserializationmechanismcomparesthe
identifier of the object being deserialized with the serialized identifier of its class (all
serializableclassesareautomaticallygivenuniqueidentifiersunlesstheyexplicitlyspe-
cifytheirownidentifiers)andcauses InvalidClassException tobethrownwhen
it detects a mismatch.
Perhaps you've added an instance field to a class, and you want the deserialization
mechanismtosettheinstancefieldtoadefaultvalueratherthanhave readObject()
throwan InvalidClassException instance.(Thenexttimeyouserializetheob-
ject, the new field's value will be written out.)
You can avoid the thrown InvalidClassException instance by adding a
static final long serialVersionUID = long integer value ;
declarationtotheclass.The long integer value mustbeuniqueandisknownas
a stream unique identifier (SUID) .
During deserialization, the JVM will compare the deserialized object's SUID to its
class'sSUID.Iftheymatch, readObject() won'tthrow InvalidClassExcep-
tion when it encounters a compatible class change (e.g., adding an instance field).
However, it will still throw this exception when it encounters an incompatible class
change (e.g., changing an instance field's name or type).
Note Whenever you change a class in some way, you must calculate a new SUID
and assign it to serialVersionUID .
TheJDKprovidesa serialver toolforcalculatingtheSUID.Forexample,togen-
erate an SUID for Listing 8-14 ' s Employee class, change to the directory containing
Employee.class and execute serialver Employee . In response, serial-
ver generates the following output, which you paste (except for Employee: ) into
Employee.java :
Employee:
static
final
long
serialVersionUID
=
-6768634186769913248L;
TheWindowsversionof serialver alsoprovidesagraphicaluserinterface(GUI)
that youmight find more convenient to use. Toaccess this GUI, specify serialver
-show .WhentheGUIappears,enter Employee intheFullClassNametextfieldand
click the Show button, as demonstrated in Figure 8-6 .
Search WWH ::




Custom Search