Java's Serialization mechanism saves the current state of an object(s) to a stream of bytes and restore an equivalent object(s) from that stream. For an object to become capable of getting serialized, it needs to implement the Serializable interface.
Java Serialization takes care of saving the object's entire "object graph", that is, a deep copy of everything the saved object needs to be restored. For this to be possible, all the objects in the object graph will need to implement Serializable.
Java Serialization takes care of saving the object's entire "object graph", that is, a deep copy of everything the saved object needs to be restored. For this to be possible, all the objects in the object graph will need to implement Serializable.
package info.icontraining.serialization;
import java.io.*;
public class TestClass implements Serializable {
private A a;
private int i;
private String s;
public TestClass() {
a = new A();
i = 10;
s = "Hello";
}
public A getA() {
return a;
}
public static void main(String args[])
throws IOException, ClassNotFoundException {
TestClass t = new TestClass();
serializeObject(t);
deserializeObject();
}
private static void serializeObject(TestClass t)
throws IOException {
FileOutputStream fs = new FileOutputStream("test.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(t);
os.close();
}
private static void deserializeObject()
throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream("test.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
TestClass t = (TestClass) ois.readObject();
ois.close();
System.out.println("i of TestClass = " + t.i);
System.out.println("i of B = " + t.getA().getB().getI())
}
}
class A implements Serializable {
private B b;
A() {
b = new B();
}
public B getB() {
return b;
}
}
class B implements Serializable {
private int i;
B() {
i = 20;
}
public int getI() {
return i;
}
}