This is some information on the Java 6 certification that I prepare. This information is not very well structured and it is most of the time an answer to the questions that come when I read the SCJP 6 book (Bates and Sierra). *** AS OF 5 OF MARCH 2010, I AM SCJP 6.0 ***

Tuesday, January 12, 2010

12 - Example with transient (2)

public class AnotherClass {
    int aInt = 7;
}

public class Main implements Serializable {

    int bInt = 5;
    AnotherClass aAnotherClass = new AnotherClass();

    public static void main(String[] args) throws Exception {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Main.ser"));
        Main aMain = new Main();
        System.out.println("" + aMain.bInt + aMain.aAnotherClass.aInt);
        oos.writeObject(aMain);
        oos.close();
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Main.ser"));
        aMain = (Main) ois.readObject();
        ois.close();
        System.out.println("" + aMain.bInt + aMain.aAnotherClass.aInt);
    }
}

run:
57
Exception in thread "main" java.io.NotSerializableException: javaapplication35.AnotherClass
        at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1156)
        at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1509)
        at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1474)
        at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392)
        at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150)
        at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326)
        at javaapplication35.Main.main(Main.java:30)
Java Result: 1

As you can see it is not possible to serialize a reference to an object that is NOT serializable !


No comments:

Post a Comment

Followers