Serializable Interface

An instances of a class (an object) can be stored in a file, transmitted to another system, and later reconstituted from the file to be used in the same or in another program.  To declare a class has this functionality, the class must implement the Serializable interface. The interface does not require any methods but recommends the class provide a field to hold a serial number.

private static final long serialVersionUID = 42L;

If a class is serializable, all its subclasses are serializable.

Below is an example of a Serializable class.

class MyClass implements Serializable {
    private static final long serialVersionUID = 1L;
    private int i;

    public MyClass (int i) {
        this.i = i;
    }
    public String toString() {
        return "i: " + i;
    }
}

In order to write an instance (obj) of a Serializable class (MyClass) to a file with name fileName we use the writeObject method in the ObjectOutputStream class.

ObjectOutputStream  os = new
    ObjectOutputStream(new FileOutputStream(fileName));
os.writeObject(obj);

To reconstitute an object from a file named fileName, we use the readObject method in the ObjectInputStream class.

ObjectInputStream is = new
    ObjectInputStream(new FIleInputStream(fileName));
MyClass obj2 = (MyClass) is.readObject();

In order to deserialize a method, the system must have access to a .class file for the serialized instance stored in the file.  When deserializing the instance, the JRE verifies that the serialized object in the file is an instance of the class defined in the .class file.  If it is not, a ClassNotFoundException is thrown.

Example

Below is a driver that creates an instance of MyClass, stores it in a file named “serial.obj”, then reconstitutes a new object from the same file.

import java.io.*;

public class Driver {
    public static void main(String[] args) {
        MyClass original = new MyClass("Hello", 100);
        writetoClass(original, “serial.obj”);

        MyClass duplicate = readFromFile(“serial.obj”);
        System.out.println(duplicate.toString());
    }

    public static void writeToFile(MyClass original, String fileName) {
        try {
            ObjectOutputStream  os = new
                ObjectOutputStream(new FileOutputStream(fileName));
            os.writeObject(original);
        } catch (IOException e) {
            System.out.println("IOException during serialization");
        }
    }

    public static MyClass readFromFile(String fileName) {
        try {
            ObjectInputStream is = new
                ObjectInputStream(new FIleInputStream("serial.obj"));
            return (MyClass) is.readObject();
        } catch (Exception e) {
            System.out.println("Exception during deserialization");
        }
    }
}

 

 

 

 

© 2017 – 2019, Eric. All rights reserved.