Sunday, 31 March 2013

Serializing Child with Parent not Serializable

This is interesting to see when you serialize a child which has one of the parent not serializable, on deserialization constructor of that parent class gets called.

In Given example while deserialization constructor of GrandParent will be called.

Note: While deserialization it calls only the default constructor of such parent. If non-serializable parent lack default constructor it will throw exception for "no valid constructor".

class Grandparent {
// must need default constructor
    public Grandparent() {
        System.out.println("A");
    }
}

 class Parent extends Grandparent implements Serializable {
    public Parent() {
        System.out.println("B");
    }
}
 class Child extends Parent {
    public Child() {
        System.out.println("C");
    }
}


public class TestSerialization{
    public static void main(String args[]) throws IOException, ClassNotFoundException {
        System.out.println("Serialization ....");
        ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream("/object"));
        out.writeObject(new Child());
        System.out.println("Now Deserialization ....");
        ObjectInputStream in = new ObjectInputStream( new FileInputStream("/object"));
        Object obj = in.readObject();
        System.out.print(obj + " -- " + obj.getClass());
    }
}

OUTPUT
----------


Serialization ....
A
B
C
Now Deserialization ....
A
co.uk.sample.Child@d2906a -- class co.uk.sample.Child



No comments:

Post a Comment