Externalization in Java
Externalization in Java is an alternative to serialization that allows more control over the serialization process. It enables an object to customize its own serialization and deserialization methods. Unlike standard serialization, where the process is automatic, externalization requires the object to implement specific methods to write and read its state.
In Java, the Externalizable
interface is used for externalization. Let's see an example:
import java.io.*;
// Externalizable class
class Employee implements Externalizable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public Employee() {
// Required for Externalizable
}
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(name);
out.writeInt(age);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
name = (String) in.readObject();
age = in.readInt();
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class ExternalizationExample {
public static void main(String[] args) {
// Create an instance of Employee
Employee employee = new Employee("John Doe", 30);
try {
// Serialize the object to a file
FileOutputStream fileOut = new FileOutputStream("employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
employee.writeExternal(out);
out.close();
fileOut.close();
System.out.println("Employee object externalized and saved to employee.ser");
} catch (IOException e) {
e.printStackTrace();
}
// Deserialize the object from the file
try {
FileInputStream fileIn = new FileInputStream("employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Employee deserializedEmployee = new Employee();
deserializedEmployee.readExternal(in);
in.close();
fileIn.close();
System.out.println("Deserialized Employee:");
System.out.println("Name: " + deserializedEmployee.getName());
System.out.println("Age: " + deserializedEmployee.getAge());
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
In this example, we have a class Employee
that implements the Externalizable
interface. The Employee
class has two fields: name
and age
. We create an instance of the Employee
class and externalize it by invoking the writeExternal
method to write the object's state to a file using ObjectOutputStream
.
During deserialization, we read the externalized object from the file using ObjectInputStream
and invoke the readExternal
method to read the object's state. Finally, we can access the fields of the deserialized object.
Externalization provides flexibility for an object to choose which fields to serialize and how to serialize them. It allows custom logic during the serialization and deserialization process.