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

13 - Example with transient (3)

What can we do to avoid the serialization of an object that is not serializable ? The object have to be marked transient and null is returned from the deserialization.


import java.io.Serializable;

public class AnotherClass {
    int aInt = 7;
}


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Main implements Serializable {

    int bInt = 5;
    transient 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!=null?aMain.aAnotherClass.aInt:"null"));
    }
}



run:
57
5 null

No comments:

Post a Comment

Followers