Java Reference
In-Depth Information
Subclasses of
Element
will inherit the implementation of the
Serializable
interface but there is a
tiny snag. At the time of writing,
none
of the
Shape
classes in the
java.awt.geom
package are
serializable, and we have been using them all over the place.
We are not completely scuppered though. Remember that you can always implement the
readObject()
and
writeObject()
methods in a class and then implement your own serialization.
We can take the data that we need to recreate the required
Shape
object and serialize that in our
implementation of the
writeObject()
method. We will then be able to reconstruct the object from
the data in the
readObject()
method. Let's start with our
Element.Line
class.
Serializing Lines
Just to remind you of one of the things we discussed back in the I/O chapters, the
writeObject()
method that serializes objects must have the form:
private void writeObject(ObjectOutputStream out) throws IOException {
// Code to serialize the object...
}
Our
Element.Line
objects are always drawn from (0, 0) so there's no sense in saving the start point in
a line - it's always the same. We just need to serialize the end point, so add the following to the
Element.Line
class:
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeDouble(line.x2);
out.writeDouble(line.y2);
}
We don't need to worry about exceptions that might be thrown by the
writeDouble()
method at this
point. These will be passed on to the method that calls
writeObject()
. The coordinates are public
members of the
Line2D.Double
object so we can reference them directly to write them to the stream.
The rest of the data relating to a line is stored in the base class,
Element
, and as we said earlier they
are all taken care of. The base class members will be serialized automatically when an
Element.Line
object is written to a file. We just need the means to read it back.
To recap what you already know, the
readObject()
method to deserialize an object is also of a
standard form:
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
// Code to deserialize an object...
}
For the
Line
class, the implementation will read the coordinates of the end point of the line and
reconstitute
line
- the
Line2D.Double
member of the class. Adding the following method to the
Element.Line
class will do that:
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException {