J
Jim Garrison
When is it acceptable for readObject and writeObject to call other
public/protected object methods?
The following code is from a version of GregorianCalendar in IBM's
WebSphere Application Developer product. The 'override' of readObject
was introduced in the latest fixpack for WSAD, and breaks some of my
code.
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException { /*ibm@56174*/
stream.defaultReadObject(); /*ibm@56174*/
setGregorianChange(new Date(gregorianCutover)); /*ibm@56174*/
} /*ibm@56174*/
I had created a subclass of GregorianCalendar to represent immutable
dates, and had overridden setGregorianChange to throw an
UnsupportedOperationException. Needless to say, after this update any
attempt to deserialize an instance of my subclass fails.
My intuitive feeling is that serialization and deserialization are
supposed to happen "under the covers", and should not involve the
object's public or protected interfaces. The reason for this is that
public and protected methods can be overridden by subclasses, and
therefore their behavior is not guaranteed to be whatever the base
class thinks it is. This can lead to fatal errors, as it did in this
case.
I would guess that readObject and writeObject should limit themselves
to either direct internal manipulation or use of private interfaces
only.
I'd really like some comments from more-knowledgeable Java folks on
this one.
TIA
public/protected object methods?
The following code is from a version of GregorianCalendar in IBM's
WebSphere Application Developer product. The 'override' of readObject
was introduced in the latest fixpack for WSAD, and breaks some of my
code.
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException { /*ibm@56174*/
stream.defaultReadObject(); /*ibm@56174*/
setGregorianChange(new Date(gregorianCutover)); /*ibm@56174*/
} /*ibm@56174*/
I had created a subclass of GregorianCalendar to represent immutable
dates, and had overridden setGregorianChange to throw an
UnsupportedOperationException. Needless to say, after this update any
attempt to deserialize an instance of my subclass fails.
My intuitive feeling is that serialization and deserialization are
supposed to happen "under the covers", and should not involve the
object's public or protected interfaces. The reason for this is that
public and protected methods can be overridden by subclasses, and
therefore their behavior is not guaranteed to be whatever the base
class thinks it is. This can lead to fatal errors, as it did in this
case.
I would guess that readObject and writeObject should limit themselves
to either direct internal manipulation or use of private interfaces
only.
I'd really like some comments from more-knowledgeable Java folks on
this one.
TIA