0Pricing
Java Academy · Lesson

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

  1. Java Serialization Basics
  2. transient Fields and serialVersionUID
  3. Custom Serialization: writeObject and readObject
  4. Modern Alternatives: JSON and Protocol Buffers
← Back to Java Academy