Printable Version Printable Version

Java Object Serialization – Developer’s Guide

Jul 16th, 2009 | By admin | Category: Java

Class is the heart of Java programming and object is a representative of the class. In day to day java programming , we create object and use that in many different ways.But the life span of an object is till the JVM(Java Virtual Machine) is up. Once JVM is down , there is no existence of the object you have created.But Java has a mechanism which allows you to store(save) your object ( let me say, object state) and you can use the stored object under a different JVM , in a different application or after restarting your own JVM. Isn’t it cool ? This mechanism (let me call it , API) is called Java Serialization API which is really small, strong and easy to use.


Object Serialization

Object Serialization


Object serialization is the process of saving an object state to the sequence of bytes and restoring the object state after rebuilding those bytes together for any future use. let me start with the basic process of object serialization.An object of a class can be made serialized if the class implements a marker interface java.io.Serializable.
Lets Create an User class to serialize the User object and restore it to use in the future. As mentioned , User class should implement java.io.Serializable marker interface to serialize the User class object.

Listing 1 : Create a User class which implements java.io.Serializable

package com.etechguide.java.serialization;

import java.io.Serializable;
import java.util.Date;

public class UserData implements Serializable {
	// Name of the User
	private String userName;
	// Employee Id of the User
	private String empId;
	// Creation date of the User in the database
	private Date creationDate;
	// Default constructor
	public UserData(){

	}
	/**
	 * Method to get the User Name
	 * @return String
	 */
	public String getUserName() {
		return userName;
	}
	/**
	 * Method to get the Employee Id
	 * @return String
	 */
	public String getEmpId() {
		return empId;
	}
	/**
	 * Method to get the User Creation
	 * Date and time
	 * @return java.util.Date instance
	 */
	public Date getCreationDate() {
		return creationDate;
	}
	/**
	 * Method to set the User name
	 * @param userName
	 */
	public void setUserName(String userName) {
		this.userName = userName;
	}
	/**
	 * Method to set the Employee Id
	 * @param empId
	 */
	public void setEmpId(String empId) {
		this.empId = empId;
	}
	/**
	 * Method to set the user creation
	 * Date and time
	 * @param creationDate
	 */
	public void setCreationDate(Date creationDate) {
		this.creationDate = creationDate;
	}
}

We would serialize the User object in the form of bytes to the file system. Remember Java i/o programming for file reading and writing ? Yes , we are going to do something of that sort. Look at the following code which should serialize the User object to a file system file , say , user.ser.

Listing 2 : Serializing the User object to file system file user.ser

package com.etechguide.java.serialization;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;

public class PersistUser {

	public static void main(String[] args) {
		String fileName = "user.ser";
		String userName = "admin";
		String empId = "889776";
		Date userCreationDate = new Date();

		UserData userData = new UserData();
		FileOutputStream fos = null;
		ObjectOutputStream out = null;

		try {
			fos = new FileOutputStream(fileName);
			out = new ObjectOutputStream(fos);
			userData.setUserName(userName);
			userData.setEmpId(empId);
			userData.setCreationDate(userCreationDate);
			out.writeObject(userData);
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

Look at the line number 27 in Listing 2 .The method writeObject(Object object) does the main tricks of writing object’s state to file system in the form of sequence of bytes.We have created on User object at the line number 17 and set the values to it.We have created java.io.FileOutputStream object and java.io.ObjectOutputStream object to call the writeObject method. Once run the above main() method , one file called user.ser should be created. This file would have all the state stored for the user object. You can take this file (user.ser) to any other Jvm , any other application and restore the User object state to use it further.Before we proceed to restore the state of the User object under a new jvm or a new application , there are few things to remember and take care.
1. You should have the User.java class accessible to the new Jvm or the new application to restore the object’s state.You can access the class from a jar file in your new environment.
2. User Object class files and the methods are not saved into the user.ser file , only the state of the Object which is saved.
If you have understood both the pointers stated above , lets go ahead and restore the object information.

Listing 3 : Restoring the User object state from user.ser

package com.etechguide.java.serialization;

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

public class RestoreUserState {

	public static void main(String[] args) {
		// Specify the full path of the
		// user.ser file
		String filename = "user.ser";
		UserData userData = null;
		FileInputStream fis = null;
		ObjectInputStream in = null;
		try {
			fis = new FileInputStream(filename);
			in = new ObjectInputStream(fis);
			userData = (UserData) in.readObject();
		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		System.out.println("Accessing Date and Time = " + new Date().toString());
		System.out.println("user name = " + userData.getUserName());
		System.out.println("emp id = " + userData.getEmpId());
		System.out.println("creation Date and Time = "
				+ userData.getCreationDate().toString());
	}
}

Look at the line number 20 in the Listing 3.This is where the restoration is taking place.Look more closely to understand , we are casting the return type of readObject method to the User type.It is why we need the access to User class in the new jvm / new application.in.readObject() returns a java.lang.Object by-default. lets run the program and see the output.
Output :

Accessing Date and Time = Thu Jul 16 13:07:02 IST 2009
user name = admin
emp id = 889776
creation Date and Time = Thu Jul 16 12:28:21 IST 2009

It is clear from output of the program , User object’s state was saved at Thu Jul 16 12:28:21 IST 2009 with information like user name = admin and employee id=889776. We can clearly see the difference between the time we restore the User object , i.e , Thu Jul 16 13:07:02 IST 2009 and the creation time.
So intention is clear now. We have tried to create an User object with it’s user name , employee id and creation date properties . Then we saved the state of it to the file system and restored it for future use. Cool , huh ? The basic process of doing object serialization is very simple and straight-forward. But there are few more things that we should know about object serialization.

Learning 1 : java.lang.Object is not Serializable

Parent call of all java class is java.lang.Object. Object class does not implement the marker interface java.lang.Serializable , hence a direct object of java.lang.Object class can not be serialized. So why all java objects can not be serialized automatically. But there are plenty ready made serialized type available in java. Few of them are array , String , Swing components etc.

Learning 2 : Do Thread serializable?

The answer is No. Thread is not serializable like Socket.No one would try to use the Thread belongs to one application under one jvm to another jvm for another application.

Learning 3 : Want to serialize an object which has a non-serializable field.

Yes , you can serialize an object which has a non-serializable state declared like instance of a Thread. But there is a difference. You have to mark the variable declaration as,
transient private Thread myThread explicitly. look at the declaration, the key word transient to force the java serialization not to store the state of the field while storing the object’s state.

Learning 4 : I would like to serialize an object and send through metwork.

Yes possible. One of the main purpose of using Java Serialization mechanism is , one should serialize / de-serialize the object network.

  • Share/Save/Bookmark
Tags:

Leave Comment