Java serialization


Java provides an object serialization mechanism. In this mechanism, an object can be represented as a byte sequence, which includes the object's data, information about the object's type, and storage. The type of data in the object.

After writing the serialized object to the file, you can read it from the file and deserialize it, that is, the type information of the object, the data of the object, and the data in the object Types can be used to create new objects in memory.

The entire process is Java Virtual Machine (JVM) independent, that is, an object serialized on one platform can deserialize the object on a completely different platform.

Classes ObjectInputStream and ObjectOutputStream are high-level data streams that contain methods for serializing and deserializing objects.

The ObjectOutputStream class contains many writing methods to write various data types, with the exception of one particular method:

public final void writeObject(Object x) throws IOException

The above method serializes an object and sends it to the output stream. The similar ObjectInputStream class contains the following methods for deserializing an object:

public final Object readObject() throws IOException, 
                                 ClassNotFoundException

This method takes the next object from the stream and deserializes the object. Its return value is Object, therefore, you need to convert it to the appropriate data type.

To demonstrate how serialization works in Java, I will use the Employee class mentioned in the previous tutorial. Suppose we define the following Employee class, which implements the Serializable interface.

public class Employee implements java.io.Serializable
{
   public String name;
   public String address;
   public transient int SSN;
   public int number;
   public void mailCheck()
   {
      System.out.println("Mailing a check to " + name
                           + " " + address);
   }
}

Please note that for an object of a class to be serialized successfully, two conditions must be met:

The class must implement the java.io.Serializable object.

All properties of this class must be serializable. If a property is not serializable, the property must be marked as ephemeral.

If you want to know whether a Java standard class is serializable, check the documentation for that class. Checking whether an instance of a class can be serialized is very simple, just check whether the class implements the java.io.Serializable interface.


Serialized objects

The ObjectOutputStream class is used to serialize an object. The following SerializeDemo example instantiates an Employee object and serializes the object to a file.

After the program is executed, a file named employee.ser is created. The program does not produce any output, but you can understand what the program does by studying the code.

Note: When serializing an object to a file, according to Java's standard convention, the file is given a .ser extension.

import java.io.*;

public class SerializeDemo
{
   public static void main(String [] args)
   {
      Employee e = new Employee();
      e.name = "Reyan Ali";
      e.address = "Phokka Kuan, Ambehta Peer";
      e.SSN = 11122333;
      e.number = 101;
      try
      {
         FileOutputStream fileOut =
         new FileOutputStream("/tmp/employee.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in /tmp/employee.ser");
      }catch(IOException i)
      {
          i.printStackTrace();
      }
   }
}

Deserialization object

The DeserializeDemo program below instantiates deserialization, and /tmp/employee.ser stores the Employee object.

import java.io.*;
public class DeserializeDemo
{
   public static void main(String [] args)
   {
      Employee e = null;
      try
      {
         FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         e = (Employee) in.readObject();
         in.close();
         fileIn.close();
      }catch(IOException i)
      {
         i.printStackTrace();
         return;
      }catch(ClassNotFoundException c)
      {
         System.out.println("Employee class not found");
         c.printStackTrace();
         return;
      }
      System.out.println("Deserialized Employee...");
      System.out.println("Name: " + e.name);
      System.out.println("Address: " + e.address);
      System.out.println("SSN: " + e.SSN);
      System.out.println("Number: " + e.number);
    }
}

The compilation and running results of the above program are as follows:

Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101

The following points should be noted here:

The try/catch code block in the readObject() method attempts to catch the ClassNotFoundException exception . For the JVM to be able to deserialize an object, it must be a class that can find the bytecode. If the JVM cannot find the class during deserialization of the object, a ClassNotFoundException is thrown.

Note that the return value of the readObject() method is converted into an Employee reference.

When the object is serialized, the value of the attribute SSN is 111222333, but because the attribute is transient, the value is not sent to the output stream. So the SSN attribute of the Employee object after deserialization is 0.