Friday 24 February 2012

Serialization in java


Serialization:
       The process of saving an object in a persistance media i.e, in a file system or a database is called serialization.
      
       Serialization can be achieved by using a marker interface Serializable.
       An Object is said be serializable if and only if the corresponding class implements Serializable interface.
       serializable interface present in java.io package and doen't contain any methods & hence it is a marker interface
       If we are trying to serialize, non serializable object, we will get runtime exception saying not serializable exception.
      
       Only state of an object is stored using serialization & hence we can't methods,constuctors,IIBs or any other executable blocks.
       Even static attributes also can't be serialized as they are not a part of the object
       Any type of attributes either primitive or derived can be serialized if they are non static (even null values & final attributes also).
       There is no restiction of any access level.
      
       *while performing serialization  if we don't want to send the value of a variable, to meet the security contraint, such type of variables we have to declare with transient keyword.
       For transient variable jvm sends default value, istead of  original value.
      
       *if a class uses any derived attributes other  then that particular class also must implemented with serilizable interface.
       if we don't do so ,we get NotSerializaleException.
      
       *This rule doen't apply for wrapper & string classes because they have already implemented Serializable interface.There is no restriction in case of primitive attributes.
       if a class is implemented with Serializable interface then its sub-classes upto n-level are elizible for serialization.The subclasses should take of super class public & protected members while serializing.
       * we can't serialize abstract classes & interfaces but objects of their types constucted using annonymous innerclasses can be serialized.
      

The important classes used in serialization are File, FileOutputStream,ObjectOutputStream.


Steps of performing Serializable operation
1)Create a File class object with desired name
2)Create an object to FileOutputStream by sending the refernce of the File Object
3)Create an Object of ObjectOutputStream by sending the refernce of FileOutputStream
4)Employ the writeObject() method of ObjectOutputStream class by sending the object which has to be serialized ex:writeObject(new A());
5)calling statements of constuctors of both ObjectOutputStream,FileOutputStream classes raise a checked exception named IOException.It should be taken care
6) soon after the input oprations are got over we have to flush() method for the purpose stated above.Then after the file should be closed.
7)closing of files should be in reverse order in which they are opened.Because first the inner resource should be closed then only outer one.
8)Both flush() & close() raise a checked exception named IOException.It should be taken care

Note: When serializing an object to a file, the standard convention in Java is to give the file a .ser extension.

java program to demontrate serialization of an object
package com.usr.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Person implements Serializable{
        int age;
        String name;
     String city;
        transient String password;
        double height;
        double weight;
}
public class SerializationDemo {
public static void main(String[] args) {
       File file=new File("person.ser");
       FileOutputStream fos=null;
       ObjectOutputStream oos=null;
       try{
              fos=new FileOutputStream(file);
              oos=new ObjectOutputStream(fos);
              Person p=new Person();
              p.age=26;
              p.city="bangalore";
              p.height=170.23;
              p.weight=62.34;
              p.password="pass";
              p.name="sachin";
              oos.writeObject(p);
              System.out.println("object serialized...");
       }
       catch(IOException ex){
              ex.printStackTrace();
       }
       finally{
              try{
                     if(oos!=null){
                           oos.flush();
                           oos.close();
                     }
              }
              catch(IOException ex){
                     ex.printStackTrace();
              }
              try{
                     if(fos!=null){
                           fos.flush();
                           fos.close();
                     }
              }
              catch(IOException ex){
                     ex.printStackTrace();
              }
       }
}
}

OUTPUT
object serialized...