Java Reference
In-Depth Information
putStream object. The readObject() and writeObject() methods for the stream call these methods to
perform I/O on the stream if you implement them.
Even though it isn't necessary in this class, let's take the PolyLine class as a demonstration vehicle for
how this works. To do your own serialization, the class would be:
class PolyLine implements Serializable {
// Serialized input method
private void readObject(ObjectInputStream in) throws IOException {
// Code to do the serialized input...
}
// Serialized output method
private void writeObject(ObjectOutputStream out)
throws IOException, ClassNotFoundException {
// Code to do the serialized output...
}
// Class definition as before...
}
These two methods must have exactly the same signature in any class where they are required, and they
must be declared as private .
In a typical situation, you should use the default serialization operations provided by the object stream
and just add your own code to fix up the data members that you want to take care of — or have to in
the case of a non-serialized base class. To get the default serialization done on input, you just call the de-
faultReadObject() method for the stream in your serialization method:
private void readObject(ObjectInputStream in) throws IOException {
in.defaultReadObject(); // Default serialized input
// Your code to do serialized input...
}
You can get the default serialized output operation in a similar fashion by calling the defaultWriteOb-
ject() method for the stream object that is passed to your output method. Obviously, you must read back
the data in exactly the same sequence as it was written, so the two methods have essentially mirror opera-
tions on the same sequence of data items.
Serialization Problems and Complications
For most classes and applications, serialization works in a straightforward fashion. You will have situations
that can cause confusion, though. One such situation is when you want to write several versions of the same
object to a file. You need to take care to ensure that the result is what you want. Suppose you write an object
to a file — a PolyLine object, say. A little later in your code, you modify the PolyLine object in some way,
by moving a point perhaps, and you now write the same object to the file again in its modified state. What
happens? Does the file contain the two versions of the object? The answer — perhaps surprisingly — is no.
Let's explore this in a little more detail with a revised version of the TryPolylineObjects example.
TRY IT OUT: Serializing Variations on an Object
Search WWH ::




Custom Search