Handling Class Evolution with Externalizable
What you'll learn: How to manage versioning and maintain backward compatibility when using manual serialization with Externalizable.
The Versioning Challenge
When you implement Externalizable, you take complete control of serialization—but you also take complete responsibility for versioning. Unlike Serializable with its serialVersionUID safety net, Externalizable doesn't automatically detect version mismatches. If your class evolves (fields added, removed, or reordered), old serialized data may break during deserialization.
Think of it like this: You're writing a custom file format. If you change the format later, you need to handle both the old and new versions yourself—there's no automatic compatibility layer.
Techniques for Backward Compatibility
1. Write a Version Number First
Start your writeExternal by writing a version identifier:
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(2); // Version 2 of your format
out.writeUTF(name);
out.writeInt(age);
out.writeBoolean(active); // New field in version 2
}
2. Read Conditionally Based on Version
In readExternal, read the version first and handle each format:
public void readExternal(ObjectInput in) throws IOException {
int version = in.readInt();
name = in.readUTF();
age = in.readInt();
if (version >= 2) {
active = in.readBoolean();
} else {
active = true; // Default for old data
}
}
3. Always Read What You Write
Maintain strict symmetry within each version. If version 1 wrote three strings, version 1 logic must read exactly three strings.
Key Takeaway: With Externalizable, version compatibility is your responsibility—embed version markers in your serialized data and write conditional deserialization logic to handle older formats gracefully.