Serialization: readObject() and self method calls?

From: Jim Garrison (jhg_at_athensgroup.com)
Date: 10/20/03


Date: Mon, 20 Oct 2003 16:18:31 -0500

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



Relevant Pages

  • Serialization: readObject() and self method calls?
    ... When is it acceptable for readObject and writeObject to call other ... The following code is from a version of GregorianCalendar in IBM's ... I would guess that readObject and writeObject should limit themselves ...
    (comp.lang.java.programmer)
  • Re: Overriding existing Serializeable writeObject ?
    ... >problem I found out is that my implementation of writeObject and ... >readObject() for my rendering frame is completely ignored!! ... Coaching, problem solving, economical contract programming. ...
    (comp.lang.java.programmer)
  • writeObject and readObject problem
    ... i very blur with the use of writeObject and readObject, ... i try to send the button pressed event, the writeObject is ok but the ... At server, i need do a function to forward the object ...
    (comp.lang.java.programmer)
  • ClassNotFoundException reading object from ObjectInputStream
    ... I'm learning how to serialize objects. ... writeObject an object to it. ... readObject the object from it. ...
    (comp.lang.java)