Serialization Proxy Pattern
Serialize an invariant-bearing object through a serialization proxy so the constructor validation always runs on read.
Code
import java.io.*;
public class Invoice implements Serializable {
private static final long serialVersionUID = 1L;
private final String customer;
private final int cents;
public Invoice(String customer, int cents) {
if (cents < 0) {
throw new IllegalArgumentException("negative cents");
}
this.customer = customer;
this.cents = cents;
}
// serialization proxy pattern: the wire format never carries the real class
private static class Proxy implements Serializable {
private static final long serialVersionUID = 1L;
private final String customer;
private final int cents;
Proxy(Invoice invoice) {
this.customer = invoice.customer;
this.cents = invoice.cents;
}
private Object readResolve() {
return new Invoice(customer, cents); // goes back through the constructor, so deserialization cannot bypass the invariants
}
}
private Object writeReplace() {
return new Proxy(this);
}
private void readObject(ObjectInputStream in) throws InvalidObjectException {
throw new InvalidObjectException("proxy required");
}
public static void main(String[] args) throws Exception {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(buffer)) {
out.writeObject(new Invoice("acme", 4950));
}
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()))) {
Invoice restored = (Invoice) in.readObject();
System.out.println("restored: " + restored.customer + " " + restored.cents);
}
}
}How the snippet works
Serialization Proxy Pattern reduces to the classes Invoice, private and Proxy and the functions Invoice, readResolve and writeReplace.
try-with-resources closes each declared resource automatically on every exit path. Invalid states are rejected up front: it throws IllegalArgumentException and InvalidObjectException instead of continuing with bad data.
What to watch for
- Nothing arrives from a registry; the language ships every API used.
Using it
Signature: public Invoice(String customer, int cents)
The run emits 1 labeled section — restored: — one per step.
The demo flow inside main is Invoice — run the file to see it end to end.
Key statements
return new Invoice(customer, cents); // goes back through the constructor, so deserialization cannot bypass the invariants
}
throw new IllegalArgumentException("negative cents");
throw new InvalidObjectException("proxy required");
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- How are precondition violations signaled?
- The code throws `IllegalArgumentException` and `InvalidObjectException`. Handle it at the call site or let it propagate deliberately.
- What does Serialization Proxy Pattern print when run?
- Running the file directly is enough — expect labeled output lines such as `restored:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.