Object Serialization And De-Serialization In Java To Filesystem

Object Serialization:
In computer science, in the context of data storage and transmission, serialization is the process of converting an object into a sequence of bits so that it can be persisted on a storage medium (such as a file, or a memory buffer) or transmitted across a network connection link. When the resulting series of bits is reread according to the serialization format, it can be used to create a semantically identical clone of the original object. For many complex objects, such as those that make extensive use of references, this process is not straightforward.

This process of serializing an object is also called deflating or marshalling an object. The opposite operation, extracting a data structure from a series of bytes, is deserialization (which is also called inflating or unmarshalling).

Advantages Of Object Serialization:
Serialization has a number of advantages. It provides:

  • A method of persisting objects which is more convenient than writing their properties to a text file on disk, and re-assembling them by reading this back in.
  • A method of issuing remote procedure calls, e.g., as in SOAP
  • A method for distributing objects, especially in software componentry such as COM, CORBA, etc.
  • A method for detecting changes in time-varying data.

Serialization In Java:
Java provides automatic serialization which requires that the object be marked by implementing the java.io.Serializable interface. Implementing the interface marks the class as “okay to serialize,” and Java then handles serialization internally. There are no serialization methods defined on the Serializable interface, but a serializable class can optionally define methods with certain special names and signatures that if defined, will be called as part of the serialization/deserialization process. The language also allows the developer to override the serialization process more thoroughly by implementing another interface, the Externalizable interface, which includes two special methods that are used to save and restore the object’s state.

There are three primary reasons why objects are not serializable by default and must implement the Serializable interface to access Java’s serialization mechanism.

  • Not all objects capture useful semantics in a serialized state. For example, a Thread object is tied to the state of the current JVM. There is no context in which a deserialized Thread object would maintain useful semantics.
  • The serialized state of an object forms part of its class’s compatibility contract. Maintaining compatibility between versions of serializable classes requires additional effort and consideration. Therefore, making a class serializable needs to be a deliberate design decision and not a default condition.
  • Serialization allows access to non-transient private members of a class that are not otherwise accessible. Classes containing sensitive information (for example, a password) should not be serializable or externalizable.


The standard encoding method uses a simple translation of the fields into a byte stream. Primitives as well as non-transient, non-static referenced objects are encoded into the stream. Each object that is referenced by the serialized object and not marked as transient must also be serialized; and if any object in the complete graph of non-transient object references is not serializable, then serialization will fail. The developer can influence this behavior by marking objects as transient, or by redefining the serialization for an object so that some portion of the reference graph is truncated and not serialized.

It is possible to serialize Java objects through JDBC and store them into a database.

While Swing components do implement the Serializable interface, they are not portable between different versions of the Java Virtual Machine. As such, a Swing component, or any component which inherits it, may be serialized to an array of bytes, but it is not guaranteed that this storage will be readable on another machine. [Source of this text Wikipedia]

The following program demonstrates how any object can be serialized. The first class is a simple object which has to be serialized/deserialized. The second class serializes and saves the object to the file, and then reads the object back from the file.

The Object to Serialize

package com.kushal.serialization;

/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified 09/01/2009 mm-dd-yyyy
 */
import java.io.Serializable;

public class MyObjectToSerialize implements Serializable {

	private String firstName;

	private String lastName;

	private int age;

	public MyObjectToSerialize(String firstName, String lastName, int age) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}

	public String toString() {
		return firstName + " " + lastName + ", " + age;
	}

}

That Class that does the serialization/deserialization job.

package com.kushal.serialization;
/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified 09/01/2009 mm-dd-yyyy
 *
 * A class that saves and loads a serialized object.
 */
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectSerialization {

	/**
	 * Saves an object to the file
	 */
	private static void saveObject(Serializable object, String filename)
			throws IOException {
		ObjectOutputStream objstream = new ObjectOutputStream(
				new FileOutputStream(filename));
		objstream.writeObject(object);
		objstream.close();
	}

	/**
	 * Loads an object from the file
	 */
	private static Object loadObject(String filename)
			throws ClassNotFoundException, IOException {
		ObjectInputStream objstream = new ObjectInputStream(
				new FileInputStream(filename));
		Object object = objstream.readObject();
		objstream.close();
		return object;
	}

	public static void main(String[] args) {
		MyObjectToSerialize original = new MyObjectToSerialize("Christopher","Walken", 64);
		System.out.println("Original Object:t" + original);
		try {
			saveObject(original, "C:/object.ser");
			MyObjectToSerialize loaded = (MyObjectToSerialize) loadObject("C:/object.ser");
			System.out.println("Loaded Object:tt" + loaded);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}



Java serialization and version control:
The Java serialization mechanism provides an approach for version control. At the heart of Java serialization is the ObjectOutputStream class. It implements the computeSerialVersionUID() method to compute the suid during object serialization. This computed suid is then written to the serialized stream as a part of the serialized object. This suid in the stream serves as a marker to denote the version of the serializable class with which it is compatible. See Figure 2 for a sample of metadata stored in a serialized object. [Source of this text: JavaWorld]