🔧 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
Method | Purpose |
---|---|
writeObject() | Customize what gets serialized |
readObject() | Customize how data is restored |
defaultWriteObject() | Writes default fields |
defaultReadObject() | Reads default fields |
transient | Excludes field from default serialization |
✅ Use Case | Encryption, compression, transformation, versioning |