Java Reference
In-Depth Information
Serializing Classes Yourself
Earlier we identified situations where the default serialization we used in the example won't work - one
occurs if your class has a superclass that is not serializable. As we said earlier, to make it possible to overcome
this, the superclass must have a default constructor, and you must take care of serializing the fields inherited
from the superclass yourself. If the superclass does not have a default constructor and you do not have access
to the original definition of the superclass, you have a problem with no obvious solution.
Another situation is where your class has fields that don't travel well. If you use the hashCode()
method that your classes will inherit from Object , then the hashcode() value for an object will be
derived from its internal address, which will not be the same when you read the object from a file. You
may have a class with vast numbers of fields with zero values, for instance, that you may not want to
have written to the file. These are also cases where do-it-yourself serialization is needed.
To implement and control the serialization of a class yourself, you must implement two private
methods in the class: one for input from an ObjectInputStream object, and the other for output to
an ObjectOutputStream object. The readObject() and writeObject() methods for the stream
will call these methods to perform I/O on the stream if you implement them.
Even though it isn't necessary in this class, we will take the PolyLine class as a demonstration vehicle
for how this works. To do our own serialization, the class would be:
class PolyLine implements Serializable {
// Class definition as before...
// 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...
}
}
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 will want to 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 defaultReadObject() 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...
}
Search WWH ::




Custom Search