How has customizing serialization (readObject/writeObject) changed in recent Java versions?

Customizing serialization in Java using the readObject and writeObject methods allows developers to have more control over the serialization process. In recent Java versions (Java SE 14 and beyond), enhancements have been made to improve the flexibility and security of serialization.

Changes in Custom Serialization

With the introduction of features such as records and sealed classes, the way we handle serialization has evolved. Records provide a compact syntax for creating data-carrying classes, while sealed classes allow for better control over class hierarchies. This means that custom serialization can be better tailored to the structure of these new types.

Example of Custom Serialization

private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.defaultWriteObject(); // Default serialization out.writeInt(customField); // Custom field serialization } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); // Default deserialization customField = in.readInt(); // Custom field deserialization }

Java Serialization Custom Serialization readObject writeObject Java SE 14 Records Sealed Classes