Sunday, April 6, 2025

Externalizable

 

 What is an Externalizable Interface?

The Externalizable interface is part of Java’s serialization mechanism. It gives complete control over the serialization process, unlike the Serializable interface where the JVM automatically serializes all non-transient fields.

When you implement Externalizable, you decide how the object is saved and restored by implementing two methods:

  • writeExternal(ObjectOutput out)
  • readExternal(ObjectInput in)

Use cases:

Use it when:

  • You want fine-grained control over what data gets serialized.
  • You want to improve performance by serializing only the necessary fields.
  • You need custom logic for serialization/deserialization.

Example:

import java.io.*;
class Employee implements Externalizable {
private String name;
private int age;
private transient double salary; // transient, won't be handled automatically
// No-arg constructor is mandatory
public Employee() {
System.out.println("No-arg constructor called");
}
public Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
// Serialization logic
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeUTF(name);
out.writeInt(age);
out.writeDouble(salary); // manually serializing even the transient field
}
// Deserialization logic
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
name = in.readUTF();
age = in.readInt();
salary = in.readDouble(); // manually reading it back
}
@Override
public String toString() {
return "Employee{name='" + name + "', age=" + age + ", salary=" + salary + "}";
}
}

No comments:

Post a Comment

CompletableFuture

  Welcome back to  our concurrency series ! In our first discussion, we likely touched on the traditional models of threading. Today, we’re ...