Saturday, December 17, 2011

Serailization & Deserialization in java

An object becomes serailizable only when its class implements Serializable Interface.
Serializable Object means
1.This Object can move across multiple JVM
2.This Object state can be stored in files.

All Wrapper class are Serializable ,means it can do the above things

transient:-
Let us say a Serializable class "UserDetails"  has 3 member variables
class UserDetails implements Serializable
{
 String username="raja";
String password="raja";
String email="raja@gmail.com";
Demo d;
}

UserDetails ud=new UserDetails();

If i will create the object of this class,and store it in file/move that object across network,password will also be saved/moved in file/network,which is certainly not wat I want.
To restrict certain variable to participate in Serialization,We use transient keyword.

Note:d is the object of Demo class,If Demo class has not implemented Serializable interface,ud fails to Serialize the Object.

eg    transient String password="raja";
------------------------------------------------------------------------------------------------------------
Test.java
------------------------------------------------------------------------------------------------------------
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Test implements Serializable
{
        int i=10,j=20;
        transient int k=30;
}
---------------------------------------------------------------------------------------------------------
SerializationDemo.java
---------------------------------------------------------------------------------------------------------
public class SerializationDemo
{
public static void main(String s[]) throws Exception
{
      Test t1=new Test();
      System.out.println("Read  value from object");
      System.out.println(t1.i+":"+t1.j+":"+t1.k);
     
      //writing object into file
      FileOutputStream fos=new FileOutputStream("c:/serialized.txt");
      ObjectOutputStream oos=new ObjectOutputStream(fos);
      oos.writeObject(t1);
      oos.close();
     
      //reading data from file and constructing new object
      FileInputStream fis=new FileInputStream("c:/serialized.txt");
      ObjectInputStream ois=new ObjectInputStream(fis);
      Test t2=(Test)ois.readObject();
      System.out.println("Read  value of New Object");
      System.out.println(t2.i+":"+t2.j+":"+t2.k);
     
      System.out.println("Address of T1 :"+t1+"\n Address of T2 :"+t2);
 }
}
-------------------------------------------------------------------------------------------------------------


No comments:

Post a Comment