Java Reference
In-Depth Information
constructor also takes a boolean argument that specifies whether the
field refers to an unshared objectthat is, one written by writeUnshared or
read by readUnshared . The serialization mechanism needs to know where
to find these ObjectStreamField objects, so they must be defined in the
static, final array called serialPersistentFields .
The fields x , y , width , and height are marked transient because they are
not serializedduring serialization these new fields must be converted in-
to appropriate values of the original fields so that we preserve the seri-
alized form. So writeObject uses an ObjectOutputStream.PutField object to
write out the old form, using x and y as the old x1 and y1 , and calculating
x2 and y2 from the rectangle's width and height . Each put method takes
a field name as one argument and a value for that field as the otherthe
type of the value determines which overloaded form of put is invoked
(one for each primitive type and Object ). In this way the default serial-
ization of the original class has been emulated and the serialized format
preserved.
When a Rectangle object is deserialized, the reverse process occurs. Our
readObject method gets an ObjectInputStream.GetField that allows access
to fields by name from the serialized object. There is a get method for
returning each primitive type, and one for returning an Object referen-
ce. Each get method takes two parameters: the name of the field and
a value to return if it is not defined in the serialized object. The return
value's type chooses which overload of get is used: A short return value
will use the get that returns a short , for example. In our example, all
values are double : We get the x1 and y1 fields to use for one corner of
the rectangle, and the old x2 and y2 fields to calculate width and height .
Using the above technique the new Rectangle class can deserialize old
rectangle objects and a new serialized rectangle can be deserialized by
the original Rectangle class, provided that both virtual machines are us-
ing compatible versions of the serialization stream protocol. The stream
protocol defines the actual layout of serialized objects in the stream re-
gardless of whether they use default serialization or the serialized field
objects. This means that the serialized form of an object is not depend-
ent on, for example, the order in which you invoke put , nor do you have
 
Search WWH ::




Custom Search