Externalizable
is an interface in Java (part of java.io
) that gives the programmer complete control over the serialization process.
Unlike
Serializable
, where Java handles serialization automatically,Externalizable
requires the class to explicitly implement how the object’s state is written and read.
Interface Definition
public interface Externalizable extends Serializable {
void writeExternal(ObjectOutput out) throws IOException;
void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;
}
Code language: PHP (php)
Simple Program: Custom Serialization Using Externalizable
LotusJavaPrince wants to store Mahesh’s login details but exclude the password and manually serialize the fields he wants.
import java.io.*; class User implements Externalizable { private String username; private transient String password; // Transient but we handle it manually // Required public no-arg constructor public User() {} public User(String username, String password) { this.username = username; this.password = password; } // Custom serialization public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(username); // password deliberately not written } // Custom deserialization public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { username = (String) in.readObject(); // password not read } public void display() { System.out.println("Username: " + username); System.out.println("Password: " + password); // will be null } } public class ExternalizableExample { public static void main(String[] args) { User user = new User("Mahesh", "secret123"); // Serialize try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("user_ext.ser"))) { oos.writeObject(user); System.out.println("User serialized using Externalizable."); } catch (IOException e) { e.printStackTrace(); } // Deserialize try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("user_ext.ser"))) { User restored = (User) ois.readObject(); System.out.println("Restored user:"); restored.display(); // Password will be null } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } }
Output:
User serialized using Externalizable.
Restored user:
Username: Mahesh
Password: null
Code language: JavaScript (javascript)
Externalizable
gives fine-grained control over serialization, unlike Serializable
which is automatic.It’s powerful in performance-sensitive or security-critical applications.But it puts the responsibility on the developer to handle all read/write logic correctly.