THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

private void readObjectNoData() throws ObjectStreamException


If, as an object is deserialized, the serialized data lists the superclass as a known superclass then the
superclass's readObject method will be invoked (if it exists), otherwise the superclass's
readObjectNoData method will be invoked. The readObjectNoData method can then set appropriate
values in the object's superclass fields.


20.8.6. Serialized Fields


The default serialization usually works well, but for more sophisticated classes and class evolution you may
need to access the original fields. For example, suppose you were representing a rectangle in a geometric
system by using two opposite corners. You would have four fields: x1, y1, x2, and y2. If you later want to
use a corner, plus width and height, you would have four different fields: x, y, width, and height.
Assuming default serialization of the four original fields you would also have a compatibility problem: the
rectangles that were already serialized would have the old fields instead of the new ones. To solve this
problem you could maintain the serialized format of the original class and convert between the old and new
fields as you encounter them in readObject or writeObject. You do this using serialized field types to
view the serialized form as an abstraction and to access individual fields:


public class Rectangle implements Serializable {
private static final
long serialVersionUID = -1307795172754062330L;
private static final
ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("x1", Double.TYPE),
new ObjectStreamField("y1", Double.TYPE),
new ObjectStreamField("x2", Double.TYPE),
new ObjectStreamField("y2", Double.TYPE),
};
private transient double x, y, width, height;


private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
ObjectInputStream.GetField fields;
fields = in.readFields();
x = fields.get("x1", 0.0);
y = fields.get("y1", 0.0);
double x2 = fields.get("x2", 0.0);
double y2 = fields.get("y2", 0.0);
width = (x2 - x);
height = (y2 - y);
}


private void writeObject(ObjectOutputStream out)
throws IOException
{


ObjectOutputStream.PutField fields;
fields = out.putFields();
fields.put("x1", x);
fields.put("y1", y);
fields.put("x2", x + width);
fields.put("y2", y + height);
out.writeFields();
}
}

Free download pdf