Sunday, January 12, 2014

Serialization in Java

 

Serialization:

Serialization is a process of writing the object state into a file system with extension .ser and recreatign object state from that file(this is called deserialization). Generally objects are stored in the Memory. In order to store the object permanently we can use the Serialization process.

In order to make any object as Serialization we need to implement with java.io.Serializable interface. Serializable interface is marker interface which doesn't have any method but it tells to the compiler this class is serializable.

Serialization process is JVM independent. It means an object can be serialized on one platform and deserialized on an different platform or same platform.

The process of serializing an object is also called marshalling an object. The process of deserializing an object is also called unmarshalling.

Serialization has a number of advantages. It provides:

Serialization can be achived two ways:
  1. Object itself should be qualifiy as a Serializable
  2.  Already implemented Seriablizable interfaces.

To make an object is serializable we can use the ObjectOutputStream class and for deserializable we can use the ObjectInputStream class.

In ObjectOutputStream class contains a lot of methods in that one method called writeObject() by using this method we can make the object as serializable.
public final void writeObject(Object obj) throws IOException;

In the same way in ObjectInputStream class contains a method called readObject() by using this method we can make the object as deserializable.
public final Object readObject() throws IOException, ClassNotFoundException;

The return type of readObject() is Object, so we need to type cast into appropriate data type.

By default all of the fields serializable while doing serialization. If you don't want any field as serializable, then mark that field as transient.

Employee.java
------------------------------------

package com.ranga;

import java.io.Serializable;

/**
 * Created by ranga on 1/12/14.
 */

public class Employee implements Serializable {
  private static final long serialVersionUID = 9986183183l;
  private long id;
  private String firstName;
  private String lastName;
  private int age;
  private String address;

  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public String getAddress() {
    return address;
  }

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

  @Override
  public String toString() {
    return "Employee{" +
        "id=" + id +
        ", firstName='" + firstName + '\'' +
        ", lastName='" + lastName + '\'' +
        ", age=" + age +
        ", address='" + address + '\'' +
        '}';
  }

}

SerializationDemo.java
------------------------------------

package com.ranga;

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

/**
 * Created by ranga on 1/12/14.
 */

public class SerializationDemo {
  public static void main(String[] args) {
    Employee employee = new Employee();
    employee.setId(143);
    employee.setFirstName("Ranga");
    employee.setLastName("Reddy");
    employee.setAge(25);
    employee.setAddress("MPL, Chittoor, AP");

    FileOutputStream fileOutputStream = null;
    ObjectOutputStream objectOutputStream = null;

    try {
      fileOutputStream = new FileOutputStream( new File("employee.ser"));
      objectOutputStream = new ObjectOutputStream(fileOutputStream);
      objectOutputStream.writeObject(employee);
      System.out.println("Employee Object Serialization Done Successfully.");
    } catch(Exception ex) {
      ex.printStackTrace();
    } finally {
       if(objectOutputStream != null) {
         try {
           objectOutputStream.close();
         } catch(Exception ex) {
           ex.printStackTrace();
         }
       }
      if(fileOutputStream != null) {
        try {
          fileOutputStream.close();
        } catch(Exception ex) {
          ex.printStackTrace();
        }
      }
    }
  }
}

Output:
------------------------------------
Employee Object Serialization Done Successfully.

DeSerializationDemo.java
------------------------------------
package com.ranga;

import java.io.*;

/**
 * Created by ranga on 1/12/14.
 */
public class DeSerializationDemo {
  public static void main(String[] args) {
    FileInputStream fileInputStream = null;
    ObjectInputStream objectInputStream = null;

    try {
      fileInputStream = new FileInputStream(new File("employee.ser"));
      objectInputStream = new ObjectInputStream(fileInputStream);
      Employee employee = (Employee) objectInputStream.readObject();
      System.out.println("Employee Info: "+employee);
    } catch(Exception ex) {
      ex.printStackTrace();
    } finally {
      if(objectInputStream != null) {
        try {
          objectInputStream.close();
        } catch(Exception ex) {
          ex.printStackTrace();
        }
      }
      if(fileInputStream != null) {
        try {
          fileInputStream.close();
        } catch(Exception ex) {
          ex.printStackTrace();
        }
      }
    }
  }
}

Output:
------------------------------------
Employee Info: Employee{id=143, firstName='Ranga', lastName='Reddy', age=25, address='MPL, Chittoor, AP'}

If a super class is implementing Serializable interface, then all sub classes are eligible for Serialization.

Example:

public class Person implements Serializable {

}
public class Employee extends Person {

}

By default, all wrapper classes are implemented Serializable.

Limitations:
  1. File size is considerable more because it contains meta information.
  2. Less performance if more transient attributes.
So in order to overcome the above limitations we can use the Externilization. We can see this one in next tutorial.

0 comments: