April 1, 2011

Java Serialization Example

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.


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;
   }
}

3 comments:

  1. Very Nice article , you have indeed covered topic in details with benchmarking result and graphics.

    Thanks
    Javin
    Top 10 Java Serialization Interview Question

    ReplyDelete
  2. Hi,
    I am highly impressed with this blog in serialization. It provides us a good amount of information about this topic. We can also refer following links for more information about this

    http://jksnu.blogspot.com/2011/01/serializable-externalizable.html

    ReplyDelete
  3. Thanks for the Example Dinesh!

    ReplyDelete