Video in progress
How does Java serialization get around encapsulation and invariants?
When a Serializable class is deserialized, its constructor is not called: the fields are filled directly from the bytes. So the checks in the constructor don't run, and a forged byte stream can create an object in an invalid state.
📖 Answer
public final class Period implements Serializable {
private final LocalDate start, end;
public Period(LocalDate start, LocalDate end) {
if (start.isAfter(end)) throw new IllegalArgumentException();
this.start = start; this.end = end;
}
}
The constructor forbids start > end. But by editing the bytes by hand you can get exactly such a Period through readObject. In practice, serialization is a "hidden public constructor" with no checks at all.
Ways to protect yourself:
- re-check the invariant inside
readObject(and make defensive copies of mutable fields); - the serialization proxy pattern:
writeReplacewrites an inner proxy, andreadResolverebuilds the object through the normal constructor; - for a singleton, use
readResolveor an enum, otherwise deserialization creates a second instance; - records have solved this problem: since Java 16, record deserialization goes through the canonical constructor, so the checks in a compact constructor run.
The bigger picture: Java's built-in serialization is discouraged today, because it has been the source of many deserialization vulnerabilities. Between services people use JSON/Protobuf, and the same formats in caches. If you use it anyway, restrict the allowed classes with ObjectInputFilter (Java 9+).
Sign up to mark studied questions and save your progress.