WHAT IS SERIALIZATION ?

It is the process of writing the state of an object to a byte stream. This is useful to save the state of one or more objects.When an object has to be transferred over a network ( typically through rmi or EJB) this is used. don't include the transient and static variables.
variable's value as part of the object's serialized state.

import java.io.*;
class myclass implements Serializable
{
transient int x;
String str;
char c;
myclass(int x,String str,char c){
this.x=x;
this.str=str;
this.c=c;
}
public String toString(){return "x="+x+"\nstr="+str+"\nc="+c;}
};
class demo
{
public static void main(String[] args)throws Exception{
myclass obj=new myclass(10,"bhabani",'a');
FileOutputStream fos=new FileOutputStream("hi.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(obj);
oos.flush();
oos.close();
}
};

GETTING THE OBJECT(DESERIALIZATION)
import java.io.*;
class demo1
{
public static void main(String[] args)throws Exception{
myclass obj1;
FileInputStream fis=new FileInputStream("hi.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
obj1=(myclass)ois.readObject();
ois.close();
System.out.println(obj1);
}
};

In the second program the out put is
x=0
str=bhabani
c=a
Here x is zero because this is declared as transient.
So it never comes in serialization.

NOTE:
If you try to serialize an object of a class which implements serializable, but the object includes a reference to an non-serializable class then a ‘NotSerializableException’ will be thrown at runtime.

Serialization Hierarchy:
If a class reside in the an object tree then how it will be serialized. The rule is when you serialize an object, the whole inheritance hierarchy is serialized till the first non-serializable class of that object.
Example:
class A{
   public int x;
}
class B extends A{
   public int y;
}
public class Bean extends B implements Serializable {
   int z;
   public static void main(String[] args)throws Exception {
       Bean obj = new Bean();
       FileOutputStream out = new FileOutputStream("xyz");
       ObjectOutputStream oOut = new ObjectOutputStream(out);
       obj.x = 1;
       obj.y = 11;
       obj.z = 111;
       oOut.writeObject(obj);
       FileInputStream in = new FileInputStream("xyz");
       ObjectInputStream oIn = new ObjectInputStream(in);
       Bean b = (Bean)oIn.readObject();
       System.out.println(b.z+"--"+b.y+"--"+b.x);
   }
}
See the output is 111--0--0.
Because classes A and B are not serializable. So it does not come in serialization.
Now make the class B Serializable, Then you will get output like this
111--11--0. A does not come because  it is not serializable.
Now make all the super class (A) Serializable, You will get the out put like this,
111--11--1.

No comments:

Post a Comment