Java Reference
In-Depth Information
Example 9−3: CompactIntList.java (continued)
int newsize = in.readInt();
resize(newsize);
this.size = newsize;
// Now read that many values from the stream
for(int i = 0; i < newsize; i++) {
short n = in.readShort();
if (n != Short.MIN_VALUE) data[i] = n;
else data[i] = in.readInt();
}
}
/** A main() method to prove that it works */
public static void main(String[] args) throws Exception {
CompactIntList list = new CompactIntList();
for(int i = 0; i < 100; i++) list.add((int)(Math.random()*40000));
CompactIntList copy = (CompactIntList)Serializer.deepclone(list);
if (list.equals(copy)) System.out.println("equal copies");
Serializer.store(list, new File("compactintlist.ser"));
}
}
Serialization and Class Versioning
One of the features of Example 9-3 is that it includes a version number in the seri-
alization 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 han-
dles 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 rep-
resented 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 seri-
alized 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 is serialized by one version of a class, it can't be deserialized by a version
that has a different version number.
Thus, when you make changes to a serializable class, even minor changes that
don't affect the serialization format, you break serialization compatibility between
versions. For example, our IntList class really ought to have a set() method that
sets the value of a specified element of the list. But if you add this method, the
new version of the class can't deserialize objects serialized by the old version. The
Search WWH ::




Custom Search