• The Externalizable interface in Java is a marker interface that allows for custom serialization of an object.
  • Classes that implement Externalizable must provide a public no-arg constructor and implement the readExternal and writeExternal methods.
  • The writeExternal method is used to write the object’s state to an ObjectOutputStream
  • the readExternal method is used to read the object’s state from an ObjectInputStream.
  • This allows for more control over the serialization process and can be useful for optimizing the serialization of large or complex objects.

Externalizable interface in Java:

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class Person implements Externalizable {
    private String name;
    private int age;

    // default constructor required for deserialization
    public Person() {}

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeUTF(name);
        out.writeInt(age);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        name = in.readUTF();
        age = in.readInt();
    }
}

The class above defines a Person class with a name and age. It implements the Externalizable interface and provides a public no-arg constructor as required by the interface. The writeExternal method writes the name and age fields to an ObjectOutputStream using the writeUTF and writeInt methods. The readExternal method reads the name and age fields from an ObjectInputStream using the readUTF and readInt methods.

To serialize an instance of this class, you can use the ObjectOutputStream like this:

Person person = new Person("John Doe", 30);
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
    oos.writeObject(person);
}

And deserialize it using the ObjectInputStream like this:

try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) {
    Person person = (Person) ois.readObject();
    System.out.println(person.getName() + ", " + person.getAge());
}

This is a simple example and it’s not recommended to use Externalizable if not needed, as it’s more complex than the Serializable interface.

Comments are closed.