Java Reference
In-Depth Information
Example 9−1: Serializer.java (continued)
System.out.println("Original data structure: " + ds);
// Output it to a file
File f = new File("datastructure.ser");
System.out.println("Storing to a file...");
Serializer.store(ds, f);
// Read it back from the file, and display it again
ds = (DataStructure) Serializer.load(f);
System.out.println("Read from the file: " + ds);
// Create a deep clone and display that. After making the copy
// modify the original to prove that the clone is "deep".
DataStructure ds2 = (DataStructure) Serializer.deepclone(ds);
ds.other.message = null; ds.other.data = null; // Change original
System.out.println("Deep clone: " + ds2);
}
}
}
Custom Serialization
Not every piece of program state can, or should be, serialized. Such things as
FileDescriptor objects are inherently platform-specific or virtual machine-depen-
dent. If a FileDescriptor were serialized, for example, it would have no meaning
when deserialized in a different virtual machine. For this reason, and also for
important the security reasons described earlier, not all objects can be serialized.
Even when an object is serializable, it may not make sense for it to serialize all its
state. Some fields may be “scratch” fields that can hold temporary or precomputed
values but don't actually hold state needed to restore a serialized object. Consider
a GUI component. It may define fields that store the coordinates of the last mouse
click it received. This information is never of interest when the component is dese-
rialized, so there's no need to bother saving the values of these fields as part of
the component's state. To tell the serialization mechanism that a field shouldn't be
saved, simply declare it transient :
protected transient short last_x, last_y; // Temporary fields for mouse pos
There are also situations where a field is not transient (i.e., it does contain an
important part of an object's state), but for some reason it can't be successfully
serialized. Consider another GUI component that computes its preferred size based
on the size of the text it displays. Because fonts have slight size variations from
platform to platform, this precomputed preferred size isn't valid if the component
is serialized on one type of platform and deserialized on another. Since the pre-
ferred size fields will not be reliable when deserialized, they should be declared
transient , so that they don't take up space in the serialized object. But in this
case, their values must be recomputed when the object is deserialized.
A class can define custom serialization and deserialization behavior (such as
recomputing a preferred size) for its objects by implementing writeObject() and
readObject() methods. Surprisingly, these methods are not defined by any
Search WWH ::




Custom Search