Custom Serialization: writeObject and readObject
Override writeObject and readObject for encryption, compression, or custom field handling.
When Default Serialization Is Not Enough
Default serialization saves all non-transient fields as-is. Sometimes you need encryption, compression, or a different representation. That's where writeObject / readObject hooks come in.
Declaring writeObject
Add a private void writeObject(ObjectOutputStream oos) method. Java calls it instead of the default mechanism. You control exactly what gets written.
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.defaultWriteObject(); // write non-transient fields normally
oos.writeUTF(encrypt(this.secret)); // write encrypted secret
}All lessons in this course
- Java Serialization Basics
- transient Fields and serialVersionUID
- Custom Serialization: writeObject and readObject
- Modern Alternatives: JSON and Protocol Buffers