Lets say that I have a program that for some reason need to handle old versions of serialized objects.
Eg: when deserializing, one of these versions may be encounter
Unfortunately, changing field types is not allowed. Supporting two (ten, hundred?) different versions would be too much of an effort. So you can utilize the readObject(ObjectInputStream in) method. And set a fixed serialVersionUID. If you haven't set it initially, use your IDE or the JDK serialver to get it, so that it appears you have only one version of the class.
If you want to change the type of a field, change its name as well. For example paws > pawsCount. The deserialization mechanism doesn't even get to the readObject(..) method if there is a type mismatch in the fields.
For the above example, a working solution would be:
class Pet implements Serializable {
private static final long serialVersionUID = 1L;
long pawsCount; // handle marsian centipedes
boolean sharpTeeth;
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject();
GetField fields = in.readFields();
int paws = fields.get("paws", 0); // the 0 is a default value
this.pawsCount = paws;
}
}
The fields that were added later will be set to their default values.
Btw, it might be a bit easier to use java.beans.XMLEncoder (if it is not too late for your project)