Never Use Default Serialization
The serialization algorithm is a very simple and robust algorithm. In pseudocode, it consists of the following five steps:
Check to see that the class implements
Serializable. If not, throw an instance ofNotSerializableException.Get the class for the instance. If the class description hasn’t been written out to the stream, write it out immediately.
If the class implements
Externalizable, call thewriteExternal( )method.Otherwise, see if the class implements the
writeObjectmethod. If it does, call thewriteObject( )method.Otherwise, use reflection to iterate through all the fields. For each field, write out a description of the field followed by its value.
This last step is often referred to as default serialization.
It’s what you get if you do nothing beyond adding
the words “implements
Serializable" to your class
definition. And it’s such a bad idea that you should
never use it.[16]
The problem is that default serialization encodes the exact structure of your class, down to the names of the fields, into the output stream, and it does so in a way that completely prevents any form of versioning. Suppose you want to change the internal representation of your data inside the object, but you still want to maintain some level of backward compatibility. For example, “instances serialized with the old program can still be read in with the new program.” If you just use default serialization, this is actually quite hard to achieve.
Suppose, on ...