Monthly Archives: December 2016

Java Object Serialization

Java Object Serialization

Introduction

  • Mechanism where an object can be converted to a sequence of bytes that includes the object’s data as well as information about the object’s type and the types of data stored in the object
  • Object can be serialized and stored in a file, later it can be deserialized to form an object
  • It is JVM independent. An object can be serialized in one platform and deserialized in other platform

Purpose of Serialization

Communication: Object can be serialized and transmitted to other machine over the network. it can be deserialized on other machine.

Persistence: If you want to store the state of a particular operation in a database, it can be easily serialized to a byte array, and stored in the database for later retrieval.

Cross JVM Synchronization: Serialization works across different JVMs that may be running on different architectures.

Conditions for a class to be serializable

  • The class must implement the java.io.Serializable interface or inherit that implementation from its object hierarchy
  • All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

Transiet

A field marked as transient is not serializable. It is typically used for fields that would be irrelevant when the object is unserialized, or fields that would be less-than-safe to store e.g. passwords, decrypted data etc.

serialVersionUID

  • The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization.
  • If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender’s class, then deserialization will result in an InvalidClassException.
  • A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long:
 ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
  • If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java Object Serialization Specification.
  • However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization.

Serialization Example

Serializable class – implementing  java.io.Serializable interface

package manvirbasra.com.serialization;

import java.io.Serializable;

public class Person implements Serializable {

	private static final long serialVersionUID = 6653705525140553845L;
	public String name;
	public String address;
	public transient int SIN;

}

Serialization Example

package manvirbasra.com.serialization;

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

public class SerializationExample {

	public static void main(String[] args) {
		Person p = new Person();
		p.name = "Manvir Basra";
		p.address = "Wall Street";
		p.SIN = 987654321;

		FileOutputStream fileOut = null;
		ObjectOutputStream out = null;
		try {
			fileOut = new FileOutputStream("/Users/manvirbasra/Desktop/temp/Person.ser");
			out = new ObjectOutputStream(fileOut);
                        //Serialization occurs at this line
			out.writeObject(p);
			System.out.println("Object serialized to file");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
				fileOut.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

}

De Serialization Example

package manvirbasra.com.serialization;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeSerializationExample {

	public static void main(String[] args) {
		Person p = null;
		try {
			FileInputStream fileIn = new FileInputStream("/Users/manvirbasra/Desktop/temp/Person.ser");
			ObjectInputStream in = new ObjectInputStream(fileIn);
                        //De Serialization occurs at this line
			p = (Person) in.readObject();
			in.close();
			fileIn.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			System.out.println("Person class not found");
			e.printStackTrace();
		}

		System.out.println("Deserialized class...");
		System.out.println("Name: " + p.name);
		System.out.println("Address: " + p.address);
		System.out.println("SIN: " + p.SIN);

	}

}

FAQ

1. Can child class be Serializable if parent class is not Serializable?

 

Resources