Serialization in Java

Serialization in simple words is the process of converting java object into bytes. Deserialization is the opposite action i.e., converting bytes into an java object. Serialization is mainly used in RMI,EJB,JMS,Hibernate,JPA etc.

Usage of Serialization
  1. The java object can be transported over the network in the form of bytes.At the other end, the bytes can be deserialized to create the object.For example,when making a method call within the RMI(Remote Method Invocation), objects are serialized to the underlying data stream and sent to the target remote process where they are
    deserialized and reconstructed.
  2. Saving the object state in the form of bytes in a file and then deserializing to create the object whenever needed. This functionality can be used to create deep clones of the object.
  3. Saving the object state to database in the form of Blob and then retrieving the saved state at a later point of time.This functionality can be used in business flows to save and retrieve object states during different stages of flow.

Now that we know what is Serialization and its possible usage.It’s time to know about it’s implementation in Java.

How do we implement Serialization in Java?

An object is serializable only if its class or its superclass implements the Serializable (or Externalizable) interface.The variables which are not meant to be serialized should be made transient.

In the below example we serialize the object by writing it to a file and later on reconstruct the object from the file.

package com.serialize.example;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SerializationExample implements Serializable{

private static final long serialVersionUID = 1L;
private static final String fileName =”serializationExample.ser”;
private String name;
private transient Integer version;

public Integer getVersion() {
return version;
}

public void setVersion(Integer version) {
this.version = version;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public SerializationExample(String name,Integer version) {
this.name = name;
this.version = version;
}

public static void serializeObject(SerializationExample serializationExample)
throws IOException {

FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(serializationExample);
oos.close();

}

public static SerializationExample deSerializeObject()
throws FileNotFoundException, IOException, ClassNotFoundException {

FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
SerializationExample serializationExample= (SerializationExample) ois.readObject();
ois.close();
return serializationExample;

}

public static void main(String args[]) throws IOException,
FileNotFoundException, ClassNotFoundException {

SerializationExample serializationExample = new SerializationExample(“SerializationExample”,1);
System.out.println(“Before Serialization”);
System.out.println(“Name:”+serializationExample.getName());
System.out.println(“version:”+serializationExample.getVersion());
serializeObject(serializationExample);
SerializationExample serializationExample1 = deSerializeObject();
System.out.println(“After Deserialization”);
System.out.println(“Name:”+serializationExample1.getName());
System.out.println(“version:”+serializationExample1.getVersion());
}

}
Output:

Before Serialization
Name:SerializationExample
version:1
After Deserialization
Name:SerializationExample
version:null // version is transient so it’s not serialized.

Rules for Serialization
  1. When you serialize an object, the whole inheritance hierarchy is serialized till the first non-serializable class of that object.
  2. The first non-serializable class must have an empty constructor.During deserialization, the object is not constructed using it’s constructors. Objects are instantiated using the saved state when it was serialized. Deserialization stops at the first non-serializable class and the empy constructor will be executed to initialise the fields of the non-serializable class.Therefore, we need to explicitly add empty constructor for the classes in the inheritance hierarchy which do not implement Serializable.If this is violated, we will get an InvalidClassException at runtime while deserialization.
  3. All primitive types are serializable.
  4. Transient fields are not serialized.
  5. Static fields are not serialized.
  6. If member variables of a serializable object reference to a non-serializable object, the code will compile but a RuntimeException will be thrown.Make sure that you make the object reference as transient.

Leave a Reply

Your email address will not be published. Required fields are marked *