Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Java serialization


May 10, 2021 Java


Table of contents


Java serialization

Java provides a mechanism for object serialization in which an object can be represented as a sequence of bytes that include data about the object, information about the type of object, and the type of data stored in the object.

After a serialized object is written to a file, it can be read from the file and reserated, that is, the object's type information, the object's data, and the data type in the object can be used to create a new object in memory.

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

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

The ObjectOutputStream class contains many writing methods for writing various data types, with one particular exception:

public final void writeObject(Object x) throws IOException

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

public final Object readObject() throws IOException, 
                                 ClassNotFoundException

This method removes the next object from the stream and reseries the object. It has a return value of Object, so you need to convert it to the appropriate data type.

To demonstrate how serialization works in Java, I'll use the Employee class mentioned in the previous tutorial, assuming 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);
   }
}

Note that for an object of a class to serialize successfully, two conditions must be met:

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

All properties of the class must be serialable. If there is a property that is not serialable, it must be noted as transient.

If you want to know if a Java standard class is serialized, check out the documentation for that class. I t's easy to verify that an instance of a class can be serialized, just to see if the class has implemented the java.io.Serializable interface.


Serialized objects

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

Once the program is executed, a file called employee.ser is created. The program doesn't have any output, but you can read through the code to understand what the program does.

Note: When serializing an object to a file, the standard convention for Java is to give the file 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();
      }
   }
}

The anti-serialization object

The following example of the DeserializeDemo program is deserialized, /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 results of the above program compilation run as follows:

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

Here are some important points to note:

The try/catch block in the readObject() method attempts to catch the ClassNotFoundException exception. F or a JVM that can deseries an object, it must be a class that can find bytecodes. I f the JVM cannot find the class during the deseration of the object, a ClassNotFoundException exception is thrown.

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

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