Lesson · Serialization & Data Formats
Java Serialization: one object, a byte stream, and the constructor that never runs
15 min readJava Serialization
Serializable is a marker interface with a large footprint: writing one object writes everything it can reach, reading it back skips the class constructor, and the class shape is pinned to a serialVersionUID. This is the machine, and the one place where validation belongs.
Serializable marks the graph, not the object
You call writeObject(cart) and get an exception about a completely different class: NotSerializableException: com.shop.Money. The object you asked for was fine; something it references was not, and the engine treats the whole reachable graph as the unit of work.
Serializable is a marker interface with no methods. What it buys is permission: the writer records the object's class name, its shape, and the values of its non-static, non-transient fields, following every reference it finds. If any value on that walk refuses, the whole write fails, and the exception names the class that refused.
class Cart implements Serializable { private final List<Line> lines = new ArrayList<>(); private Money total = Money.zero(); // Money has no Serializable marker } // java.io.NotSerializableException: com.shop.Money
- The class descriptor is written once per class, not once per object: class name, serialVersionUID, and one entry per serialized field.
- Field values follow, and a value that is a reference is queued and written as part of the same graph.
- Shared references survive the trip: writing the same object twice in one stream writes it once and reuses a handle, so the reader gets one shared instance, not two copies.
- transient and static fields are never written, which is the next section.
One non-serializable value anywhere in the reachable graph fails the entire write, and the exception names the offending class, not the one you called writeObject on.
transient and static: what the stream leaves behind
A transient field is skipped. Not a byte is written for it, and on the read side the field stays at its default: null for references, 0 for numbers, false for booleans. That marks a contract about rebuildability: the value can be recomputed, or the class can live without it.
A static field is skipped for a different reason. It belongs to the class in the reading JVM, not to the object in the stream. A static counter counts what the writer's JVM created, and nothing at all happens to it during a read.
class Session implements Serializable { private static final long serialVersionUID = 1L; private final String user; // state: travels private transient String token; // cache: does not travel, comes back null Session(String user) { this.user = user; this.token = user + "-token"; } }
| Field | Written? | Value after a read | Use it for |
|---|---|---|---|
| Instance field (not transient) | yes | the written value | the state you mean to persist |
| transient instance field | no | the field default (null / 0 / false) | caches, handles, locks, anything rebuildable |
| static field (any) | no | whatever the reading JVM's class already holds | class-level constants and counters |
transient removes a field from the stream, and that is all it does. If the value has to exist after a read, rebuild it in readObject; a null check in a getter is a symptom that this was forgotten.
serialVersionUID: pin the shape you mean to keep
The class descriptor carries a serialVersionUID, the writer's claim about the class shape. If you declare none, the runtime computes one from the class name, its modifiers, its interfaces and its member signatures, so changes that look cosmetic (a new method, a different interface, a reordered field list) can alter it and make old streams unreadable. Declare private static final long serialVersionUID = 1L; and the shape question becomes yours to answer.
When the UIDs differ, the read stops immediately with InvalidClassException: local class incompatible. When they match, the reader pairs fields by name and type and tolerates a certain amount of drift.
| Change since the stream was written | Still reads? | What happens to the data |
|---|---|---|
| Add an instance field | yes, with the same UID | the new field stays at its default for old data; old code reading new data discards the extra bytes |
| Remove an instance field | yes | the stored value for that field is consumed and discarded; nothing fails |
| Change a field's declared type | reads, but not the value | the descriptor pairs name and type, so the stored value no longer lines up and the field comes back at its default; treat a type change as a new field |
| Rename or move the class | no | the stream stores the class name, and an unresolvable name is ClassNotFoundException |
| Change the class hierarchy | risky | superclass fields are part of the chain, so adding or removing a Serializable superclass changes what a reader can restore |
The UID is a promise. Declare it and revise it deliberately; leave it out and the compiler derives one from details you did not know were part of the contract.
What goes on the wire, and what runs on the way back
The writer walks the graph and records, per class, a descriptor that names the class, its UID and its serialized fields; then it writes field values, using handles for objects it has already seen. The result is a program for the reader: a sequence of class descriptions and values in the order they were written.
The reader consumes it the same way. For each descriptor it finds the local class and compares UIDs, then allocates an instance without calling the class constructor. Fields are set from the stream, and then the class's own readObject runs, if it declared one. That private method is the only place where the class sees the object before anyone else does.
- Allocation without a constructor applies to ordinary Serializable classes, which is why field defaults, not initialiser expressions, are the starting point.
- The first non-serializable superclass in the chain gets its no-arg constructor called, so extending such a class without a reachable no-arg constructor fails at read time.
- Records are the exception (Java 16+): a Serializable record is reconstructed by calling its canonical constructor, and class-declared readObject and writeObject are ignored for records.
Deserialization does not call your constructor. Whatever readObject accepts becomes the object; if the class declares no readObject, the invariants are exactly the field values the stream chose.
Serialization write, wire, read
Live object · write side
Byte stream · records in order
no bytes yet
A live Session: id and name are state, tokenCache is transient, nextId is static. One writeObject(session) call starts the graph walk.
Customising the stream: readObject, readResolve, and the proxy
Two private methods change the default flow: writeObject and readObject. A readObject that begins with defaultReadObject reads the normal fields and then does whatever else the class requires, which includes rejecting state it will not accept. Throwing InvalidObjectException aborts the read.
writeReplace lets the object be swapped for a stand-in before anything is written. readResolve lets the read side return a different instance than the one it just built. Together they support the serialization proxy pattern, where the class hands out a small proxy carrying only logical state and the proxy's readResolve calls the real constructor.
Externalizable is the heavier alternative: writeExternal and readExternal replace the default mechanism entirely, and unlike Serializable, the class's public no-arg constructor runs before readExternal, so readExternal must cope with a half-built object.
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); // the normal fields first if (ceiling < 1) { throw new InvalidObjectException("ceiling must be positive"); // the read aborts } }
- readObject is validation time: the object exists, its fields came from the stream, and nothing else has seen it yet.
- writeReplace substitutes the object that actually gets written, which is where a serialization proxy starts.
- readResolve returns the instance the caller receives, which may be a different object (singletons, proxies).
- Externalizable replaces the whole mechanism, and its public no-arg constructor does run before readExternal.
The proxy pattern gives the class one door back in. The proxy holds the logical state, its UID is the only one on the wire, and its readResolve calls the real constructor, so validation runs for every deserialized instance.
The boundary this lesson stops at
Everything so far assumes a friendly writer. Now assume someone else writes the stream: readObject runs on the receiver, inside the receiver's JVM, over field values the attacker chose, before your code sees the object. That is not an accident of the API, it is the definition of the mechanism.
So the property worth designing for is not whether a class can be serialized, but who can write the bytes and which classes your reader accepts. The next lesson takes that attack apart; the one after it replaces the format.
- Every Serializable class is an entry point for every process that reads such streams with that class on its path.
- A filter limits which classes may arrive (Java 9+), and it cannot repair what an allowed class's readObject does.
- Records remove one class of risk because their canonical constructor runs, and they do not remove the risk that the payload names classes at all.
Deserializing untrusted data is code execution by design. Treat every ObjectInputStream that faces outside your process as an execution endpoint, because that is what it is.
The constructor that never runs
writeObject writes state, and the read side restores state into an object that was allocated without its constructor. Field initialisers, constructor checks and invariants never ran. Whatever readObject accepts is what your code will receive, so validation belongs there, or the class does not belong in a stream an outsider can write.
Interview angles
What does implementing Serializable actually guarantee?+
Very little: it marks the class as allowed to be written. The format, the UID rules and the lifecycle come from ObjectOutputStream, ObjectInputStream and the serialization specification.
Why is a transient field null after deserialization?+
transient fields are not written. The read side allocates the object at its defaults and never restores them, so the field holds null, 0 or false until the class rebuilds it in readObject.
What happens when serialVersionUID does not match?+
The read fails with InvalidClassException: local class incompatible, before any field is restored.
If you do not declare a UID, the runtime computes one from the class name, modifiers, interfaces and member signatures. Recompiling with a changed signature can therefore change the UID, which is why the declaration is a review item and not a leftover.
Common misconception: The computed UID only changes when you add or remove a field.
Is an object's constructor called during deserialization?+
Not for Serializable: the instance is allocated and its fields are restored, then readObject runs. The first non-serializable superclass in the chain does get its no-arg constructor called, and Externalizable and records are the other exceptions.
Externalizable classes need a public no-arg constructor because the read side calls it before readExternal. Records go through their canonical constructor, so their invariants do run.
Follow-up: So which classes can enforce invariants on the read path?
Why did a field silently reset after its type changed?+
Field data is matched by name and type together. After a type change the stored value no longer matches the descriptor, so the field comes back at its default instead of the written value. Treat it as a new field.
What is the serialization proxy pattern for?+
It gives the class one validated path back. writeReplace hands out a small proxy carrying the logical state, and the proxy's readResolve calls the real constructor, so no instance can exist without passing validation.
One extra class, and the proxy's shape becomes the compatibility surface, so field evolution on the real class stops being a stream-format question.
Follow-up: What does that cost?