I am reading the serialization chapter in Effective Java. I am trying to understand the paragraph below, which is found in the book.
If you implemen
Are there any invariants in the Person class I created? When will they be violated?
None explicitly, but imagine that other methods in the class assume that name
is never null
and would throw NullPointerException
if it ever were. In this case, the non-nullity of name
is an invariant.
I copied the code for
readObjectData()
method in theEmployee
class , but it never got called. When will the methodreadObject()
be called ?
There's no method readObjectData()
involved with serialization, this must be a typo. The readObject()
method is called every time a serialized object is deserialized.
The readObjectNoData()
method is hit for some obscure corner case when deserializing a subclass of the class that contains the method.
The advanced serialization article on the SunOracle website covers the purpose of these serialization helper methods. I suggest you start there and post any subsequent questions you may run into.
(update)
In case you’re curious, the readObjectNoData method was added in release 1.4 to cover a corner case involving the addition of a serializable superclass to an existing serializable class. Details can be found in the serialization specification Serialization, 3.5.
The referenced text is:
For serializable objects, the readObjectNoData method allows a class to control the initialization of its own fields in the event that a subclass instance is deserialized and the serialization stream does not list the class in question as a superclass of the deserialized object. This may occur in cases where the receiving party uses a different version of the deserialized instance's class than the sending party, and the receiver's version extends classes that are not extended by the sender's version. This may also occur if the serialization stream has been tampered; hence, readObjectNoData is useful for initializing deserialized objects properly despite a "hostile" or incomplete source stream.
So this can happen in two cases:
Employee
), one that extends some parent class (Person
). The JVM that originally *en*coded the object stream has a different, older version of these classes, where Person
was not yet a superclass of Employee
.