Sunday 21 September 2014

Serialization

Serialization is the process of converting object state into sequence of bytes. de-Serialization is a process to bring back the object’s state from bytes.

How to achieve serialization
If you want to serialize an object, that specific class must implement 'java.io.Serializable' interface. Serializable interface is a marker interface (It contains no methods).
import java.io.*;

public class Employee implements Serializable{
    int id;
    String firstName, lastName;
    
    Employee(int id, String firstName, String lastName){
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }
    
    public static void main(String args[]) throws Exception{
        
        /* Serialize object */
        FileOutputStream fos = new FileOutputStream("ser.out");
        ObjectOutputStream out = new ObjectOutputStream(fos);
        Employee emp = new Employee(1, "Krishna", "Arjun");
        out.writeObject(emp);
        
        /* Deserialize object */
        FileInputStream fis = new FileInputStream("ser.out");
        ObjectInputStream in = new ObjectInputStream(fis);
        Employee emp1 = (Employee)in.readObject();
        
        System.out.println(emp1.id + " " + emp1.firstName +" " +emp1.lastName);
    }
}

Output
1 Krishna Arjun

FileOutputStream fos = new FileOutputStream("ser.out");
ObjectOutputStream out = new ObjectOutputStream(fos);
Employee emp = new Employee(1, "Krishna", "Arjun");
out.writeObject(emp);

Above statements used to serialize the object and write the byte stream of the object to 'ser.out' file.

FileInputStream fis = new FileInputStream("ser.out");
ObjectInputStream in = new ObjectInputStream(fis);
Employee emp1 = (Employee)in.readObject();

Above statements are used to deserialize the object, that is written to 'ser.out' using serialization.

When you serialize an object, only the object's state will be saved, not the object's class file or methods.



                                                 Home

No comments:

Post a Comment