Java.Serialization.How can I change the default serialization/deserialization behavior?

🔧 Ways to Customize Java Serialization

If your class implements Serializable, you can define two special methods:

private void writeObject(ObjectOutputStream out) throws IOException
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException

These allow you to manually control what gets written to and read from the stream.

🧪 Step-by-Step Example

🔹 Custom Serialization with writeObject() and readObject()

import java.io.*;

public class Person implements Serializable {
    private static final long serialVersionUID = 1L;

    String name;
    transient String password; // We don’t want to store this directly

    public Person(String name, String password) {
        this.name = name;
        this.password = password;
    }

    // Custom serialization
    private void writeObject(ObjectOutputStream out) throws IOException {
        out.defaultWriteObject(); // Writes non-transient fields (like name)
        out.writeUTF(encrypt(password)); // Manually handle the transient field
    }

    // Custom deserialization
    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject(); // Reads non-transient fields
        password = decrypt(in.readUTF()); // Restore transient field manually
    }

    private String encrypt(String value) {
        return new StringBuilder(value).reverse().toString(); // Just for demo
    }

    private String decrypt(String value) {
        return new StringBuilder(value).reverse().toString();
    }
}

⚠️ Important Notes

  • Method signatures must be exactly:
private void writeObject(ObjectOutputStream out)
private void readObject(ObjectInputStream in)
  • If you forget defaultWriteObject(), only your custom data is written!
  • You can also define readObjectNoData() to handle backward compatibility (e.g. older files missing data).

🧵 TL;DR

MethodPurpose
writeObject()Customize what gets serialized
readObject()Customize how data is restored
defaultWriteObject()Writes default fields
defaultReadObject()Reads default fields
transientExcludes field from default serialization
✅ Use CaseEncryption, compression, transformation, versioning
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.