Skip to content

Java Programming

Demystifying Object Serialization in Java

With implementation of object serialization (Object Persistence), a java applications can save and load the state of objects to disk or over a network. In this article we will look into benefits/advantages of object serialization in java and how to implement this in our programs.

One of the most critical tasks in Java is serialization of an Object i.e. applications have to perform task to save and restore data. For example, when you play an online game and exit without completing it and if you restart it for the next time then you can resume the game where you left it. How this is achieved? This is accomplished by Serialization in Java, which helps us to save objects in Java to a file and later restore them as Objects in Java Class. Without serialization software will be more of a typewriter – users would have to re-type whole data to add further modifications once the application exits.

A class can enable serialization by implementing java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. Subclasses or subtype of class implementing java.io.Serializable interface will automatically be serialized. Serialization interface in java is also known as marker interface due to no fields or methods contained in it.

A marker interface is one that has no methods or fields and serves only to identify the semantics of being serializable.

If you want to allow subtypes of non-serializable classes to be serialized then subtypes of that class need to take the responsibility of saving and restoring the state of it’s supertype’s public, protected, and package fields. It can be done only if the class it extends has an accessible no-arg constructor to initialize the state of that class. If its super class do not have an accessible no-arg constructor then it is an error to declare a class Serializable and this error will be detected at runtime.

While deserialization, if an object may be encountered that does not support the Serializable interface, then NotSerializableException will be thrown and class of the non-serializable object will be identified. If you want your classes to have special handling during serialization and deserialization process you must implement special methods whose syntaxes are given below:

private void writeObject(java.io.ObjectOutputStream out) throws IOException

 private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;

 private void readObjectNoData() throws ObjectStreamException;

writeObject method:

wiriteObject() method writes the state of the object for its implementing class so that readObject() method can restore the object of corresponding class. If you want to implement a default mechanism for saving the class Object’s fields then you need to invoke it by calling out.defaultWriteObject. State of an object is saved by writeObject() method and is done by writing the individual fields to the ObjectOutputStream or by using the methods for primitive data types supported by DataOutput.

 try{

fileOutputStream = new FileOutputStream(fileName);

objectOutputStream = new ObjectOutputStream(fileOutputStream);

objectOutputStream.writeObject(listOfAccountHolders);

objectOutputStream.close();

System.out.println(“Object Persisted”);

}catch(IOException ex){

ex.printStackTrace();

}

readObject method :

Deserializing object of class is the responsibility of readObject method and it does this by reading it from the stream and restoring the classes fields, it may call in.defaultReadObject in order to invoke default mechanism for restoring non-static and non-transient fields of an object. readObject method works by using information in the stream to assign the fields of the object saved in the stream with the names and fields in the current object. This handles the case when the class has evolved to add new fields. The method does not need to concern about the state of its belonging superclasses or subclasses.

The defaultReadObject method uses information in the stream to assign the fields of the object saved in the stream with the correspondingly named fields in the current object. This handles the case when the class has evolved to add new fields.

try{

fileInputStream = new FileInputStream(fileName);

objectInputStream = new ObjectInputStream(fileInputStream);

accountHolderDetailsList = (ArrayList) objectInputStream.readObject();

objectInputStream.close();

}catch(IOException ex){ex.printStackTrace();}

catch(ClassNotFoundException ex){ ex.printStackTrace();}

Sample Application Showing Object Persisted and Restored

AccountHolderDetails.java

Java-Serialization

 

AccountHolderDetailsPersist.java

Java Serialization

 

Output-1

 

 

 

Code-Java-Serialization

 

 

Output-2                                       

 

Issue with Serialization and Its Solution

Java provides us relatively easy way to serialize an object and helps us to automate everything i.e. whenever we add new fields to an object, then they are saved automatically, without requiring modification to save and restore code. However, there may be some cases, in which this kind of automation can affect security of an application, as all information is not necessary to be transmitted over the network. The transient keyword in front of field indicates that a particular member variable should not be saved. Though this keyword is not used often but it’s important keyword to remember.

Serialization Benefits to Programmers

  • Reducing time taken to write code for saving and restoring of object’s state.
  • Eliminating complexities of save and restore operations, and avoiding the need for creating a new file format.
  • Making it easier for objects to travel over a network connection.

Hope after reading this article now you understood  the basic of serialization. Please share your queries/feedback in the comment section.

Be Sociable, Share!
    The following two tabs change content below.

    Basant Singh

    Basant is a talented software developer who is very engaged in web & cloud platforms on a daily basis. He is a contributor to codingthis.com reporting on various news and troubleshooting on various platforms. Basant is very strong in SQL and a great asset to the CodingThis community.

    Latest posts by Basant Singh (see all)