Monday, September 26, 2011

SERILIZATION example in java


[NOTE:In SERILIZATION cases for sequirity purpose if we want only some of the parameters of a class can be deserialized and some not then the solution is only pass that parameter through toString() method on that class.
If we consider the bellow example then we can see that we don't want the DOB's "year" parameter on the time of deserialization. So we simply not pass the year parameter by the toString() method.]

package Serialization;

import java.io.Serializable;

public class serializableClass implements Serializable
{

/**
*
*/
private static final long serialVersionUID = 1L;

String name;
int DOB;
int DOM;
int year;
public serializableClass(String name,int dob,int year)
{
this.name = name;
this.DOB = dob;
this.year = year;
}
public void showWish()
{
System.out.print("Good Morning!");
}
/*public String toString()
{
showWish();
return "Mr."+name+". Your date of birth is "+DOB+"/"+DOM+"/"+year;
}*/

/*If we don't want to pass the Year Of Birth of any one, then we simply don't pass the "year" parameter through toString() method.*/
public String toString()
{
showWish();
return "Mr."+name+". Your date of birth is "+DOB+"/"+DOM;
}
}


package Serialization;

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

public class mainClass
{
public static void main(String args[])
{
try
{
System.out.println("Start of serialization ******************************");
serializableClass srl = new serializableClass("Arun", 14, 1984);
srl.DOM = 02;
System.out.println(srl);
FileOutputStream fos = new FileOutputStream("serial");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(srl);

oos.close();
fos.close();
System.out.println("End of serialization *************************");

}catch(Exception e)
{
System.out.println(e);
System.exit(0);
}
try
{
System.out.println("\n");
System.out.println("Start of deserialization ************************");
serializableClass srl2;
FileInputStream fis = new FileInputStream("serial");
ObjectInputStream ois = new ObjectInputStream(fis);
srl2 = (serializableClass) ois.readObject();

System.out.println(srl2);
ois.close();
System.out.println("End of deserialization ************************");

} catch (Exception e)
{
System.out.println(e);
System.exit(0);
}
}
}

Output =>
Start of serialization ******************************
Good Morning!Mr.Arun. Your date of birth is 14/2
End of serialization *************************


Start of deserialization ************************
Good Morning!Mr.Arun. Your date of birth is 14/2
End of deserialization ************************

No comments:

Post a Comment