When I read the about the Serializable
interface in Thinking in java
, there is a sentence that says:
If you use the default
I think the key word in the documentation is "should", which means that you don't have to.
I think it's more of a best practice than anything else. If I read your code the first time and see that you defaulted the read/write on the first line, I can just say to myself "ok, done with 90% of the class", and concentrate on your custom code which takes care of all non-transient, non-static instance variables..
The most important thing is to read/write in the same order. Apart from that you are free to do as you like.
It's described in Effective Java:
If all instance fields are transient, it is technically permissible to dispense with invoking defaultWriteObject and defaultReadObject , but it is not recommended. Even if all instance fields are transient, invoking defaultWriteObject affects the serialized form, resulting in greatly enhanced flexibility. The resulting serialized form makes it possible to add nontransient instance fields in a later release while preserving backward and forward compatibility. If an instance is serialized in a later version and deserialized in an earlier version, the added fields will be ignored. Had the earlier version’s readObject method failed to invoke defaultReadObject , the deserialization would fail with a StreamCorruptedException .
Java Object Serialization Specification is vague on this subject:
Either
ObjectOutputStream
'sdefaultWriteObject
orwriteFields
method must be called once (and only once) before writing any optional data that will be needed by the correspondingreadObject
method to restore the state of the object; even if no optional data is written,defaultWriteObject
orwriteFields
must still be invoked once. IfdefaultWriteObject
orwriteFields
is not invoked once prior to the writing of optional data (if any), then the behavior of instance deserialization is undefined in cases where theObjectInputStream
cannot resolve the class which defined thewriteObject
method in question.
Here's an old thread which gives an example case when problems might occur.
And here's a JBoss AS Jira ticket with another example.
I think that's because you know what you do on both sides and do the "same" or better the according opposite ...
BUT: If some other programmer would write a deserialization against your serialization without knowing that you do not use the default, he probably will use the recommended defaultReadObject and then run into weird exceptions.