Java Serialization

Today we are going to talk about Java serialization. Serialization process is used to convert Java objects into their binary representation which can be easily stored on the drive or send via network to another Java program running on different JVM. The reverse process, converting from binary representation to Java objects is called deserialization.
By default you can serialize/deserialize:
- primitives (int, long, float, double, byte, char etc.)
- objects of class from java.lang package (like String)
- objects that implement java.io.Serializable interface

Here is an example of class that is serializable

SimpleSerializableClass

package com.itcuties.java.serialization.simple;

import java.io.Serializable;

/**
 * This class will demonstrate most basic serialization in java.
 * It shows that every primitive can be serialized. As well as every object that implements Serializable interface.
 * Fields with the keyword <b>transient</b> will be omitted during serialization.
 * Custom classes must implement the Serializable interface.
 * 
 * @author itcuties
 */
public class SimpleSerializableClass implements Serializable {
	/** This is generated serial version UID. Any number will do. This is used to point the serialization mechanism that
	 * the class has changed. If you change the number and try to deserialize previously serialized data you will get an error.*/
	private static final long serialVersionUID = 2304865599345677437L;

	/**
	 * Below are some fields that will hold the data used by the class.
	 * Any primitive and String instance can be serialized.
	 */
	private int intData;
	private float floatData;
	private String stringData;
	
	/** Final fields are serialized just like normal fields. */
	private final String finalData = "final data";
	
	/** Static fields are not serialized because they are connected with a class and not an instance of the object. */
	private static String staticData;
	
	/** The 'transient' keyword will cause the field to be ommited during serialization/deserialization. */
	private transient String notSerializableData;
	
	/** Custom classes can be serialized unless they also implement the serializable interface. */
	private CustomSerializableObject customSerializableObject;

	/**
	 * The constructor is NOT called when the object is deserialized.
	 * That is why serialization is one of the four ways to instantiate an object.
	 */
	public SimpleSerializableClass() {
		System.out.println(SimpleSerializableClass.class.getName() + ".constructor");
		staticData = "static-data";
	}
	
	public int getIntData() {
		return intData;
	}

	public void setIntData(int intData) {
		this.intData = intData;
	}

	public float getFloatData() {
		return floatData;
	}

	public void setFloatData(float floatData) {
		this.floatData = floatData;
	}

	public String getStringData() {
		return stringData;
	}

	public void setStringData(String stringData) {
		this.stringData = stringData;
	}
	
	public String getNotSerializableData() {
		return notSerializableData;
	}
	
	public void setNotSerializableData(String notSerializableData) {
		this.notSerializableData = notSerializableData;
	}
	
	public CustomSerializableObject getCustomSerializableObject() {
		return customSerializableObject;
	}
	
	public void setCustomSerializableObject(CustomSerializableObject customSerializableObject) {
		this.customSerializableObject = customSerializableObject;
	}

	@Override
	public String toString() {
		return "SimpleSerializableClass [intData=" + intData + ", floatData="
				+ floatData + ", stringData=" + stringData + ", finalData="
				+ finalData + ", notSerializableData=" + notSerializableData
				+ ", customSerializableObject=" + customSerializableObject + "]";
	}
}

This class stores reference to another serializable class

CustomSerializableObject

package com.itcuties.java.serialization.simple;

import java.io.Serializable;

/**
 * A custom class that IS serializable.
 * 
 * @author itcuties
 */
public class CustomSerializableObject implements Serializable {
	private static final long serialVersionUID = -1455333437430468800L;

	private String data;

	public CustomSerializableObject(String data) {
		this.data = data;
	}

	@Override
	public String toString() {
		return "CustomSerializableObject [data=" + data + "]";
	}
}

How to do serialization/deserialization of an object. Here is a little example on how to do it. We are going to store our object as a file (serialization) and then restore it from that file (deserialization). To serialize object we need to call writeObject method of the ObjectOuputStream. To perform deserialization we need to call readObject method of the ObjectInputStream class. Take a look:


	/**
	 * This method presents how to serialize and deserialize a simple object.
	 */
	private static void simpleSerialization() {
		System.out.println("Running simple serialization.");
		
		//first create an instance of a class and fill it with data
		SimpleSerializableClass dataToSerialize = new SimpleSerializableClass();
		dataToSerialize.setFloatData(1.234f);
		dataToSerialize.setIntData(1234);
		dataToSerialize.setStringData("1234");
		dataToSerialize.setNotSerializableData("This string will not be serialized.");
		dataToSerialize.setCustomSerializableObject(new CustomSerializableObject("Serializable object with custom data."));
		
		Main.serializeAndDeserialize(dataToSerialize, "simple-serialization.dat");
	}

	
	.
	...
	......
	...
	.

	
	/**
	 * An utility method to serialize - deserialize the given instance.
	 * 
	 * @param objectToSerialize
	 *            instance to be serialized-deserialized
	 * @param serializationFileName
	 *            serialization file name
	 * @return deserialized object
	 */
	private static Serializable serializeAndDeserialize(Serializable objectToSerialize, String serializationFileName) {
		System.out.println("Data that will be serialized: " + objectToSerialize);
		
		//open the stream where the data will be put
		ObjectOutputStream oos = null;
		try {
			FileOutputStream fos = new FileOutputStream(serializationFileName);
			
			//ObjectOutputStream is the stream used to serialize the object
			oos = new ObjectOutputStream(fos);
			
			System.out.println("Serializing the created instance.");
			oos.writeObject(objectToSerialize);
			oos.flush();
			System.out.println("Object is succesfully serialized.");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(oos != null) {
				try {
					oos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		System.out.println("Now the object will be deserialized.");
		Serializable deserializedInstance = null;
		ObjectInputStream ois = null;
		try {
			FileInputStream fis = new FileInputStream(serializationFileName);
			
			//ObjectInputStream is the stream used to deserialize the object
			ois = new ObjectInputStream(fis);
			
			deserializedInstance = (Serializable) ois.readObject();
			System.out.println("Deserialized data: " + deserializedInstance);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			if(ois != null) {
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return deserializedInstance;
	}

If you will try to perform serialization of an object that is not serializable you will end up with the java.io.NotSerializableException exception.

Download and run our code to find out for yourself how easy it is.

Download this sample code here.

This code is available on our GitHub repository as well.

2 Responses to "Java Serialization"

  1. menkouss says:

    very Nice tutoriel and very nice women

    Reply
  2. Radwan says:

    Very Nice Tut … !! :D

    Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>