Thursday, May 19, 2016

Significance of readObject() and writeObject() in Serialization

What happens if Dog is serialized and Collar is not but we want to get Collar original value when Dog is deserialized.

The two special methods you define must have signatures that look
EXACTLY like this:
private void writeObject(ObjectOutputStream os) {
// your code for saving the Collar variables
}
private void readObject(ObjectInputStream is) {
// your code to read the Collar state, create a new Collar,
// and assign it to the Dog
}

These methods let you step into the middle of serialization and deserialization.
So they're perfect for letting you solve the Dog/Collar problem: when a Dog is
being saved, you can step into the middle of serialization and say, "By the way, I'd
like to add the state of the Collar's variable (an int) to the stream when the Dog
is serialized." You've manually added the state of the Collar to the Dog's serialized
representation, even though the Collar itself is not saved.

Of course, you'll need to restore the Collar during deserialization by stepping into
the middle and saying, "I'll read that extra int I saved to the Dog stream, and use
it to create a new Collar, and then assign that new Collar to the Dog that's being
deserialized."

class Dog implements Serializable {
      transient private Collar theCollar; // we can't serialize this
      private int dogSize;

      public Dog(Collar collar, int size) {
            theCollar = collar;
            dogSize = size;
      }

      public Collar getCollar() {
            return theCollar;
      }

      private void writeObject(ObjectOutputStream os) {
            // throws IOException { // 1
            try {
                  os.defaultWriteObject(); // 2
                  os.writeInt(theCollar.getCollarSize()); // 3
            } catch (Exception e) {
                  e.printStackTrace();
            }
      }

      private void readObject(ObjectInputStream is) {
            // throws IOException, ClassNotFoundException { // 4
            try {
                  is.defaultReadObject(); // 5
                  theCollar = new Collar(is.readInt()); // 6
            } catch (Exception e) {
                  e.printStackTrace();
            }
      }
}

No comments:

Post a Comment