Java Serialization

Java serialization is a process of converting an object into a byte stream, so that the object can be saved to disk, transmitted over a network, or stored in memory, and later deserialized to convert the byte stream back into an object.

In Java, serialization is implemented throughjava.io.Serializablethe interface. This interface has no methods; it is just a marker interface used to indicate that a class can be serialized.

When you serialize an object, you wrap it into a special file that can be saved, transmitted, or stored. Deserialization, on the other hand, opens this file, reads the serialized data, and then restores it to an object for use in the program.

Serialization is a method for saving, transmitting, and restoring objects. It allows objects to be moved and shared between different computers, which is very useful for distributed systems, data storage, and cross-platform communication.

The following are the basic concepts and usage of Java serialization:

Implement the Serializable interface: To make a class serializable, you need to have the class implement the java.io.Serializable interface. This tells the Java compiler that the class can be serialized, for example:

Example

import java.io.Serializable;

public class MyClass implements Serializable {
    // class members and methods
}

Serializing an object:Use the ObjectOutputStream class to serialize an object into a byte stream. The following is a simple example:

Example

MyClass obj = new MyClass();
try {
    FileOutputStream fileOut = new FileOutputStream("object.ser");
    ObjectOutputStream out = new ObjectOutputStream(fileOut);
    out.writeObject(obj);
    out.close();
    fileOut.close();
} catch (IOException e) {
    e.printStackTrace();
}

The above code serializes the obj object to a file named "object.ser".

Deserializing an object:Use the ObjectInputStream class to deserialize an object from a byte stream. The following is a simple example:

Example

MyClass obj = null;
try {
    FileInputStream fileIn = new FileInputStream("object.ser");
    ObjectInputStream in = new ObjectInputStream(fileIn);
    obj = (MyClass) in.readObject();
    in.close();
    fileIn.close();
} catch (IOException e) {
    e.printStackTrace();
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}

The above code reads the byte stream from the "object.ser" file and deserializes it into a MyClass object.

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

The ObjectOutputStream class contains many write methods for writing various data types, but there is one special method that is an exception:

public final void writeObject(Object x) throws IOException

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

public final Object readObject() throws IOException, ClassNotFoundException

This method retrieves the next object from the stream and deserializes the object. Its return value is Object, so you need to cast it to the appropriate data type.

Example

To demonstrate how serialization works in Java, I will use the Employee class mentioned in a previous tutorial. Suppose we define the Employee class as follows; this class implements the Serializable interface.

Employee.java file code:

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 interface.

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

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


Serializing an Object

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

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

Note:When serializing an object to a file, the standard Java convention is to give the file a .ser extension.

SerializeDemo.java file code:

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(); } } }

Deserializing an Object

The DeserializeDemo program below demonstrates deserialization, with /tmp/employee.ser storing the Employee object.

DeserializeDemo.java file code:

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 execution result of the above program is as follows:

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

Here are the key points to note:

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

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

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

Other Extensions