Monday, March 10, 2014

Serialization in Java

When you are talking about object I/O, serialization comes into picture as well.

ObjectInputStream and ObjectOutputStream classes can be used to read/write serializable objects.

Serializable Interface

Not every object can be written to an output stream. Objects that can be so written are said to be serializable.

A serializable object is an instance of the java.io.Serializable interface, so the object's class must implement Serializable.

The Serializable interface is a marker interface. Since, it has no methods, you don't need to add additional code in your class that implements Serializable.

Implementing Serializable interface enables the Java serialization mechanism to automate the process of storing objects and arrays.

Java provides a built-in mechanism to automate the process of writing objects. This process is referred to as object serialization, which is implemented in ObjectOutputStream.

The process of reading objects is referred to as object deserialization, which is implemented in ObjectInputStream.

Many classes in Java API implement Serializable. Attempting to store an object that does not support the Serializable interface would cause a NotSerializableException.

When a serializable object is stored, the class of the object is encoded; this includes the class name and signature of the class, the value's of the object's instance variables, and the closure of any other objects referenced by the object.

The values of the object's static variables are not stored.

Note:
If an object is an instance of Serializable, but contains nonserializable instance data fields, can it be serialized??
The answer is No. To enable the object to be serialized, mark these data fields with the transient keyword to tell JVM to ignore them when writing the object to an object stream.

public class C implements java.io.Serializable {
          private int v1;
          private static double v2;
          private transient A v3 = new A();
}
class A { } // A is not serializable

When an object of the C class is serialized, only variable v1 is serialized. Variable v2 is
not serialized because it is a static variable, and variable v3 is not serialized because it is
marked transient. If v3 were not marked transient, a java.io.NotSerializableException would occur.

Code Example:
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ObjectSerializeTest implements Serializable {
    
    private int age;
    private String name;
    
    public void setAge(int ageVal) {
        age = ageVal;
    }
    
    public void setName(String nameVal) {
        name = nameVal;
    }
    
    public void Display() {
        System.out.println("Name: " + name + ", Age: " + age);
    }
    
    public static void main(String[] args) {
        ObjectSerializeTest obj1 = new ObjectSerializeTest();
        obj1.setAge(28);
        obj1.setName("Raghu");        
        
        FileOutputStream fops;
        try {
            fops = new FileOutputStream("raghu.txt");       
            ObjectOutputStream oos = new ObjectOutputStream(fops);
            oos.writeObject(obj1);
        }
        catch (FileNotFoundException ex) {
            Logger.getLogger(ObjectSerializeTest.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (IOException ex) {
            Logger.getLogger(ObjectSerializeTest.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        FileInputStream fips;
        try {
            fips = new FileInputStream("raghu.txt");
            ObjectInputStream oips = new ObjectInputStream(fips);
            ObjectSerializeTest obj2 = (ObjectSerializeTest)oips.readObject();
            obj2.Display();
        }
        catch (FileNotFoundException ex) {
            Logger.getLogger(ObjectSerializeTest.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (IOException ex) {
            Logger.getLogger(ObjectSerializeTest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ObjectSerializeTest.class.getName()).log(Level.SEVERE, null, ex);
        }        
    }        
}

O/P:
Name: Raghu, Age: 28


No comments:

Post a Comment