Sunday, December 15, 2013

What is Serialization and How to achieve ?

1)Serialization is the process of writing the state of the object in to a file.
state means the instance variables.

What should we need to do serialize our object ?
--------------------------------------------------------

1)Our class should implement Serializable interface.It is marker interface.
It will not have any methods..

2)What If I don't implement serializable and try to serialize the object
You will get java.io.NotSerializableException.

3)Steps to serialize StudentTo object...

a)Create StudentTo();
b)Create FileOutputStream with the file in which you want to store the
serialized state of the object.In our example I took the file name as
hello.ser.Generally it is convention to end the file name with .ser.
c)Pass FileOutputStream to ObjectOutputStream
d)Call writeObject method from ObjectOutputStream
e)Check that you will find a file created with name hello.ser

4)How to deserialize the studento from hello.ser

a)Create FileInputStream with the file name in to which you serialized the
state of the object.In our example It is hello.ser

b)Pass FileInputStream to ObjectInputStream
d)Call readObject method from ObjectInputStream
e)cast the returned Object to StudentTo

Important Points:
--------------------

1)Suppose sometimes you don't want to serialize... sensitive information like
password.Then you have to mark that instance variable as transient.
Transient means that won't participate in the serialization process.

2)Some runtime objects like JDBCConnection can't be serialized, in that
case we need to mark it as transient.

When you deserialize connection will be set to null.So to reinitalize the
connection.. we have to write a method with syntax
private void readObject(ObjectInputStream) to reinitalize the connection

When you write readObject method in your class... we can implement
our own logic to reinitalize the connection.

Call defaultReadObject--in readObject. This will initate normal deserialization process
after that you implement your own logic to get the connection again in readObject
method

Check my examples.....

3)If any superclass of the class implements Serializable... then the subclass
can be serialized with out saying implements Serializable.
 /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.jt.utils.db;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 *
 * @author Rishitha
 */
public  class ConnectionFactory {
  
  
  
    public static Connection getConnection() throws Exception{

       Class.forName("oracle.jdbc.driver.OracleDriver");
       Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","hr","hr");
       return con;
     

    }

}
  
  
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package serializationproject;

import com.jt.utils.db.ConnectionFactory;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.sql.Connection;

/**
 *
 * @author Rishitha
 */
public class HowToReinitalizeTransientVariableWithreadObject implements Serializable{
   
    private String sname;
    private String address;
    transient private Connection conn;
   
    public HowToReinitalizeTransientVariableWithreadObject(){
      
    }

   private void readObject(ObjectInputStream ois ) throws Exception{
      
       ois.defaultReadObject();
       this.conn = ConnectionFactory.getConnection();
      
   }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public HowToReinitalizeTransientVariableWithreadObject(String sname, String address) {
        this.sname = sname;
        this.address = address;
    }
   
   
   
   
    public static void main(String args[]) throws  Exception{
       
        HowToReinitalizeTransientVariableWithreadObject one = new HowToReinitalizeTransientVariableWithreadObject();
        one.setSname("Anil");
        one.setAddress("Guntur");
        System.out.println(one.getSname()+" "+one.getAddress());
        one.setConn(ConnectionFactory.getConnection());
        System.out.println(one.getConn());
     
       
         ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("hello.ser"));
        oos.writeObject(one);
       
       
       
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("hello.ser"));
       
        HowToReinitalizeTransientVariableWithreadObject copy = (HowToReinitalizeTransientVariableWithreadObject)ois.readObject();
        System.out.println("DeserName: "+copy.getSname()+ " DeserAddress "+copy.getAddress()+" deserconn:"+copy.conn);
       
 }

    public Connection getConn() {
        return conn;
    }

    public void setConn(Connection conn) {
        this.conn = conn;
    }
   
   

   
}
 
 2)
 /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package serializationproject;

import com.jt.utils.db.ConnectionFactory;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.sql.Connection;

/**
 *
 * @author Rishitha
 */
public class SerializationExampleWithTransientVariableWhichReturnsNull implements Serializable{
  
    private String sname;
    private String address;
    transient private Connection conn;
  
    public SerializationExampleWithTransientVariableWhichReturnsNull(){
     
    }

 

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public SerializationExampleWithTransientVariableWhichReturnsNull(String sname, String address) {
        this.sname = sname;
        this.address = address;
    }
  
  
  
  
    public static void main(String args[]) throws  Exception{
      
        SerializationExampleWithTransientVariableWhichReturnsNull one = new SerializationExampleWithTransientVariableWhichReturnsNull();
        one.setSname("Anil");
        one.setAddress("Guntur");
        System.out.println(one.getSname()+" "+one.getAddress());
        one.setConn(ConnectionFactory.getConnection());
        System.out.println(one.getConn());
    
      
      
      
      
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("hello.ser"));
        oos.writeObject(one);
      
      
      
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("hello.ser"));
      
        SerializationExampleWithTransientVariableWhichReturnsNull copy = (SerializationExampleWithTransientVariableWhichReturnsNull)ois.readObject();
        System.out.println("DeserName: "+copy.getSname()+ " DeserAddress "+copy.getAddress()+" deserconn:"+copy.conn);
      
        //If you observe above SOP... transient variable returned null
        //because transient variables... will not be serialized at all
        //and they don't participate in serialization process...
        //Refer example HowToReinitalizeTransientVariableWithreadObject
        //how to reinitalize transient instance variable with readObject
      
           
    }

    public Connection getConn() {
        return conn;
    }

    public void setConn(Connection conn) {
        this.conn = conn;
    }
  
  

  
}
 
 
 
 
 
 
 
 
 
 
 
 

No comments:

Post a Comment