Tuesday, 19 April 2011

What happens if an object is serializable but it includes a reference to a non-serializable object?

If you try to serialize an object of a class which implements serializable, but the object includes a reference to an non-serializable class then a ‘NotSerializableException’ will be thrown at runtime.
e.g. public class NonSerial {
    //This is a non-serializable class
}

public class MyClass implements Serializable{
    private static final long serialVersionUID = 1L;
    private NonSerial nonSerial;
    MyClass(NonSerial nonSerial){
        this.nonSerial = nonSerial;
    }
    public static void main(String [] args) {
        NonSerial nonSer = new NonSerial();
        MyClass c = new MyClass(nonSer);
        try {
        FileOutputStream fs = new FileOutputStream("test1.ser");
        ObjectOutputStream os = new ObjectOutputStream(fs);
        os.writeObject(c);
        os.close();
        } catch (Exception e) { e.printStackTrace(); }
        try {
        FileInputStream fis = new FileInputStream("test1.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);
        c = (MyClass) ois.readObject();
        ois.close();
            } catch (Exception e) {
            e.printStackTrace();
          }
    }
}
On execution of above code following exception will be thrown  –
java.io.NotSerializableException: NonSerial
            at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java)

No comments:

Post a Comment