All topics
library
intermediate

Serialization & Deserialization

Understand Java's built-in serialization, serialVersionUID, transient, and the security concerns.

Java serialization converts an object's state into a byte stream (serialization) and reconstructs it later (deserialization). A class must implement java.io.Serializable.

Serialization = freeze-drying food (preserving state for transport). Deserialization = rehydrating it. But someone could tamper with the freeze-dried packet (untrusted data = security risk).

Key Concepts

1
Key concepts: - serialVersionUID: a version identifier. If the serialized and deserialized versions differ, InvalidClassException is thrown. Always declare explicitly — if omitted, the compiler generates one from the class structure, which changes with any modification. - transient fields are excluded from serialization (passwords, caches, derived values) - static fields are not serialized (they belong to the class, not the instance) - The entire object graph is serialized — all referenced objects must also be Serializable
2
Customization: - writeObject(ObjectOutputStream) and readObject(ObjectInputStream) — custom serialization logic - writeReplace() — substitute a different object for serialization - readResolve() — substitute a different object after deserialization (used for Singleton preservation) - Externalizable interface — full control over format (must implement readExternal/writeExternal)
3
Security concerns: - Deserialization creates objects without calling constructors — can bypass validation - Untrusted deserialization is a major attack vector (Remote Code Execution) - Java 9+ added deserialization filters (ObjectInputFilter) - Prefer JSON/protobuf over Java serialization for external data exchange