Java Serialization: readResolve, writeReplace, Versioning and Security
Keep serialized Java objects correct over time and safe: readResolve and writeReplace with the serialization proxy pattern, serialVersionUID and serialver, how fields are matched between versions, ObjectInputValidation, deserialization filters, and deep copying by serialization.
kvi5hnuCode Sprout team member12 min readOn this page
The last three articles showed how serialization writes objects and how a class can shape its own data. This article deals with what happens afterwards. Deserialized objects are created without a constructor, so they can break identity rules and invariants. Classes change, so old files must still be readable. And bytes from outside may have been crafted by an attacker. Each problem has a standard answer.
readResolve: restoring identity
Deserialization always creates a new object. That's what you want for ordinary data, and wrong for classes whose instances are meant to be unique. Before enums existed, people wrote "typesafe enumerations" like this:
final class Level implements Serializable {
static final Level LOW = new Level(1), HIGH = new Level(2);
private final int value;
private Level(int value) { this.value = value; }
}
Code compares level == Level.HIGH. But after a round trip through serialization, the deserialized object is a third Level with value 2, and == fails. The fix is a readResolve method. After an object is read, the stream calls it and uses its return value in place of the object that was just read:
@Serial
private Object readResolve() throws ObjectStreamException {
return value == 1 ? LOW : HIGH;
}
The temporary copy becomes garbage, and every reference in the stream to it is resolved to the canonical instance. Better still, use an enum. Enum constants are serialized by name and always resolve to the existing constant, so identity is guaranteed without any extra code. That's also the recommended way to write a serializable singleton:
public enum Registry {
INSTANCE;
// methods
}
writeReplace and the serialization proxy
writeReplace is the mirror image. When it's present, the stream calls it before writing and serializes the returned object instead. Together the two methods support the serialization proxy pattern, which is the most robust way to serialize a class with invariants:
- Write a small private nested class (a record works well) that holds just the logical state.
- In the main class,
writeReplacereturns a proxy. - The proxy's
readResolvecreates a real object through the public constructor or a factory method, so every check runs. - The main class's
readObjectthrowsInvalidObjectException, so a crafted stream that contains the main class directly is rejected.
@Serial private Object writeReplace() { return new Proxy(num, den); }
@Serial private void readObject(ObjectInputStream in) throws InvalidObjectException {
throw new InvalidObjectException("use the proxy");
}
private record Proxy(int num, int den) implements Serializable {
@Serial private Object readResolve() { return new Fraction(num, den); }
}
The same pattern lets you choose what's stored at all. A Person entity could write a proxy holding only its database id, and the proxy's readResolve would look the person up again.
Unlike readObject and writeObject, these two methods may have any access modifier. If they're protected or package-private they're inherited by subclasses, which is rarely what you want, so private is the usual choice. Records honor both methods. Enums ignore them.
Versioning
Article 33 explained that a class without a declared serialVersionUID gets a computed fingerprint, and that almost any change to the class changes it. Then old streams fail with InvalidClassException.
To make a class evolvable, declare the UID from the start. If you already have files written by a version without one, find the computed value with the JDK's serialver tool and declare that value in all later versions:
$ serialver -classpath . com.example.Employee
com.example.Employee: private static final long serialVersionUID = 8367346051156850807L;
With matching UIDs, the stream compares the fields in the file with those of the current class, using only non-static, non-transient fields:

- A field in the stream but not in the class is read and ignored.
- A field in the class but not in the stream gets its default value:
null,0orfalse. - A field with the same name but a different type makes the classes incompatible. There's no conversion, not even from
inttolong.
The specification lists the compatible changes (adding fields, adding or removing classes in the hierarchy, adding writeObject/readObject, changing access modifiers, making a field non-static or non-transient) and the incompatible ones (deleting fields in a way the old reader can't cope with, changing a field's type, moving classes up or down the hierarchy, changing between Serializable and Externalizable, turning a class into an enum or back).
Is the default handling safe? Ignoring extra data usually is. Getting null in a field that every constructor initializes may not be. Use readObject to fill in a sensible value for a newly added field, or readObjectNoData (article 34) for a newly added superclass.
Validating deserialized objects
A crafted stream can describe an object that the constructor would never allow, such as an account with a negative balance. For a single object, check in readObject after defaultReadObject and throw InvalidObjectException. Sometimes a check needs the whole graph, for example when it compares the object with others it refers to. The ObjectInputValidation interface handles that:
@Serial
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.registerValidation(this, 0);
in.defaultReadObject();
}
@Override
public void validateObject() throws InvalidObjectException {
if (balance < 0) throw new InvalidObjectException("negative balance");
}
registerValidation can only be called from inside readObject. The callback runs once the outermost readObject call has rebuilt the whole graph. The second argument is a priority: callbacks with higher values run first. Records need none of this, since their canonical constructor runs (article 34).
Deserialization is a security boundary
Never deserialize data from a source you don't trust. Reading an object stream can:
- create objects of any serializable class on the class path, not only the ones you expect
- run the
readObject,readResolveandhashCode/equalsmethods of those classes on attacker-chosen data. Attackers combine such methods in widely used libraries into gadget chains that end in arbitrary code execution, which is how many real-world remote exploits worked. - consume huge amounts of memory or CPU, for example through enormous array lengths or deeply nested
HashSets whose hash computations explode
Where possible, use a data format that maps to explicit types, such as JSON with a schema or Protocol Buffers. If you must deserialize data that has left your process, authenticate it (for example, sign it with an HMAC and check the signature before reading), and use filters.
Deserialization filters
Filters (JEP 290, Java 9, and JEP 415, Java 17) inspect each class and some size metrics before the stream builds the object. A filter returns ALLOWED, REJECTED or UNDECIDED. A rejection aborts reading with InvalidClassException: filter status: REJECTED.
The easiest filters are patterns:
var filter = ObjectInputFilter.Config.createFilter("com.example.model.*;java.base/*;!*");
in.setObjectInputFilter(filter);
| Pattern | Meaning |
|---|---|
com.example.Item | allow this class |
com.example.* | allow classes in this package |
com.example.** | allow this package and its subpackages |
java.base/* | allow classes from the java.base module |
Prefix* | allow class names starting with the prefix |
!pattern | reject classes that match |
maxdepth=n, maxrefs=n, maxbytes=n, maxarray=n | limit graph depth, number of references, stream size, array length |
Patterns are tried left to right and the first match wins, so a final !* rejects everything not listed. You can also write a filter as a lambda over ObjectInputFilter.FilterInfo. Its serialClass() is the class being checked, or null for a pure limit check, and arrays arrive as array classes such as Object[].
Process-wide filters don't require any code changes:
- the system property
-Djdk.serialFilter=pattern, or the property of the same name in thejava.securityconfiguration file, sets a filter for everyObjectInputStreamthat doesn't set its own ObjectInputFilter.Config.setSerialFiltersets it from code, once- since Java 17, a filter factory (
ObjectInputFilter.Config.setSerialFilterFactoryor-Djdk.serialFilterFactory) chooses a filter for each stream, which lets frameworks combine the global filter with context-specific ones. Helper methodsObjectInputFilter.allowFilter,rejectFilter,mergeandrejectUndecidedClassbuild such combinations.
The JDK's own uses of serialization, such as RMI, come with built-in filters.
Deep copies through serialization
There's a cute side use. Serialize an object into a ByteArrayOutputStream and read it right back, and you have a deep copy of the whole graph, with shared references and cycles preserved:
@SuppressWarnings("unchecked")
static <T extends Serializable> T deepCopy(T obj) throws IOException, ClassNotFoundException {
var bytes = new ByteArrayOutputStream();
try (var out = new ObjectOutputStream(bytes)) { out.writeObject(obj); }
try (var in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
return (T) in.readObject();
}
}
It's much slower than a hand-written copy constructor, and it breaks on some cyclic structures. Collections like ArrayList and HashSet serialize their elements, not their internals, and rebuild themselves in readObject. If a list contains a set that contains the list, the set's readObject calls hashCode on a list that isn't fully restored, which throws NullPointerException. The demo below reproduces this.
The program
The demo simulates class evolution inside one file. It writes an object of one class, patches the class name in the bytes (the layout from article 33 makes this easy), and reads it as a different version. Then it shows identity with readResolve, a serialization proxy, validation of a tampered stream, three kinds of filters, and deep copying.
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class Solution {
// ---------- versions of one class (names of equal length so we can patch the stream) ----------
static class Emp1 implements Serializable { // "version 1.0"
@Serial private static final long serialVersionUID = 1L;
String name = "Ada"; double salary = 5000;
}
static class Emp2 implements Serializable { // "version 2.0": one more field
@Serial private static final long serialVersionUID = 1L;
String name = "Grace"; double salary = 6000; String department = "R&D";
@Override public String toString() { return name + ", " + salary + ", " + department; }
}
static class Emp3 implements Serializable { // salary changed type
@Serial private static final long serialVersionUID = 1L;
String name; String salary;
}
static class Emp4 implements Serializable { // forgot to keep the UID
@Serial private static final long serialVersionUID = 2L;
String name; double salary;
}
// ---------- identity: readResolve ----------
static final class Level implements Serializable { // a pre-enum "typesafe enumeration"
@Serial private static final long serialVersionUID = 1L;
static final Level LOW = new Level(1), HIGH = new Level(2);
private final int value;
private Level(int value) { this.value = value; }
@Serial private Object readResolve() throws ObjectStreamException {
return value == 1 ? LOW : HIGH; // replace the copy by the canonical instance
}
}
static final class Color implements Serializable { // same class without readResolve
@Serial private static final long serialVersionUID = 1L;
static final Color RED = new Color();
}
// ---------- writeReplace + serialization proxy ----------
static final class Fraction implements Serializable {
@Serial private static final long serialVersionUID = 1L;
private final int num, den;
Fraction(int num, int den) {
if (den == 0) throw new IllegalArgumentException("zero denominator");
int g = gcd(Math.abs(num), Math.abs(den)) * Integer.signum(den);
this.num = num / g; this.den = den / g;
}
static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
@Override public String toString() { return num + "/" + den; }
@Serial private Object writeReplace() { return new Proxy(num, den); }
@Serial private void readObject(ObjectInputStream in) throws InvalidObjectException {
throw new InvalidObjectException("use the proxy"); // reject streams that bypass it
}
private record Proxy(int num, int den) implements Serializable {
@Serial private Object readResolve() { return new Fraction(num, den); } // runs all checks
}
}
// ---------- ObjectInputValidation ----------
static class Account implements Serializable, ObjectInputValidation {
@Serial private static final long serialVersionUID = 1L;
long balance;
Account(long balance) { this.balance = balance; }
@Serial private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.registerValidation(this, 0);
in.defaultReadObject();
}
@Override public void validateObject() throws InvalidObjectException {
if (balance < 0) throw new InvalidObjectException("negative balance " + balance);
}
}
// ---------- helpers ----------
static byte[] save(Object obj) throws IOException {
var bytes = new ByteArrayOutputStream();
try (var out = new ObjectOutputStream(bytes)) { out.writeObject(obj); }
return bytes.toByteArray();
}
static Object load(byte[] data) throws IOException, ClassNotFoundException {
return load(data, null);
}
static Object load(byte[] data, ObjectInputFilter filter) throws IOException, ClassNotFoundException {
try (var in = new ObjectInputStream(new ByteArrayInputStream(data))) {
if (filter != null) in.setObjectInputFilter(filter);
return in.readObject();
}
}
/** Replace the class name in a stream, to simulate a file written by another version. */
static byte[] rename(byte[] data, String from, String to) {
String s = new String(data, StandardCharsets.ISO_8859_1);
return s.replace("Solution$" + from, "Solution$" + to).getBytes(StandardCharsets.ISO_8859_1);
}
static void attempt(String what, byte[] data) {
try {
System.out.println(what + ": " + load(data));
} catch (IOException | ClassNotFoundException e) {
System.out.println(what + ": " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
@SuppressWarnings("unchecked")
static <T extends Serializable> T deepCopy(T obj) throws IOException, ClassNotFoundException {
return (T) load(save(obj));
}
public static void main(String[] args) throws Exception {
System.out.println("--- versioning ---");
var e1 = (Emp2) load(rename(save(new Emp1()), "Emp1", "Emp2"));
System.out.println("old file, new class: " + e1);
var e2 = (Emp1) load(rename(save(new Emp2()), "Emp2", "Emp1"));
System.out.println("new file, old class: " + e2.name + ", " + e2.salary);
attempt("field type changed", rename(save(new Emp1()), "Emp1", "Emp3"));
attempt("UID changed", rename(save(new Emp1()), "Emp1", "Emp4"));
System.out.println("--- readResolve and writeReplace ---");
System.out.println("Level.HIGH survives as the same object: " + (deepCopy(Level.HIGH) == Level.HIGH));
System.out.println("Color.RED survives as the same object: " + (deepCopy(Color.RED) == Color.RED));
System.out.println("fraction 6/-4 round trip: " + deepCopy(new Fraction(6, -4)));
System.out.println("--- validation ---");
byte[] acct = save(new Account(100));
// balance is the last 8 bytes; make it -1
Arrays.fill(acct, acct.length - 8, acct.length, (byte) 0xFF);
attempt("tampered account", acct);
System.out.println("--- filters ---");
var data = save(new ArrayList<>(List.of(new Emp1(), "x")));
var onlyJdk = ObjectInputFilter.Config.createFilter("java.base/*;!*");
try {
load(data, onlyJdk);
} catch (InvalidClassException ex) {
System.out.println("pattern filter: " + ex.getMessage());
}
var small = ObjectInputFilter.Config.createFilter("maxarray=10;maxdepth=5");
try {
load(save(new int[1000]), small);
} catch (InvalidClassException ex) {
System.out.println("limit filter: " + ex.getMessage());
}
ObjectInputFilter custom = info -> {
Class<?> c = info.serialClass();
if (c == null) return ObjectInputFilter.Status.UNDECIDED; // a limit check, not a class
while (c.isArray()) c = c.getComponentType(); // judge Object[] by Object
if (c.isPrimitive()) return ObjectInputFilter.Status.ALLOWED;
return c.getName().startsWith("Solution$") || c.getName().startsWith("java.")
? ObjectInputFilter.Status.ALLOWED : ObjectInputFilter.Status.REJECTED;
};
System.out.println("custom filter accepts: " + load(data, custom).getClass().getSimpleName());
System.out.println("--- cloning by serialization ---");
var original = new ArrayList<>(List.of(new StringBuilder("a"), new StringBuilder("b")));
var copy = deepCopy(original);
original.get(0).append("!");
System.out.println("original " + original + ", deep copy " + copy);
var list = new ArrayList<Object>();
var set = new HashSet<Object>();
list.add(set);
set.add(list); // a cycle through a HashSet
System.out.println("copy of the set has size " + deepCopy(set).size());
try {
deepCopy(list);
} catch (NullPointerException ex) {
System.out.println("copy of the list: NullPointerException");
}
}
}
--- versioning ---
old file, new class: Ada, 5000.0, null
new file, old class: Grace, 6000.0
field type changed: InvalidClassException: Solution$Emp3; incompatible types for field salary
UID changed: InvalidClassException: Solution$Emp4; local class incompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = 2
--- readResolve and writeReplace ---
Level.HIGH survives as the same object: true
Color.RED survives as the same object: false
fraction 6/-4 round trip: -3/2
--- validation ---
tampered account: InvalidObjectException: negative balance -1
--- filters ---
pattern filter: filter status: REJECTED
limit filter: filter status: REJECTED
custom filter accepts: ArrayList
--- cloning by serialization ---
original [a!, b], deep copy [a, b]
copy of the set has size 1
copy of the list: NullPointerException
Common questions
Is an enum really the best way to write a singleton?
For a singleton that must stay unique through serialization and reflection, yes: the JVM guarantees one instance per constant, deserialization resolves by name, and reflection cannot create new enum instances. For singletons that are not serializable, a private static final field or a holder class works just as well.
How do I find out which classes my filter must allow?
Start with a logging filter that returns UNDECIDED and prints info.serialClass() while you run your tests, then turn the observed classes into an allow-list pattern ending in !*. Add limits such as maxdepth, maxrefs and maxbytes at the same time.
Is Java going to remove serialization? There are no plans to remove it, because too much existing code depends on it. OpenJDK has discussed better replacements for years ("serialization 2.0", based on records and explicit marshalling), but nothing has been finalized. Treat built-in serialization as legacy: maintain it where it is used, and choose other formats for new designs.
Are JSON libraries safe from deserialization attacks? Mostly, as long as you deserialize into specific types you name. The danger returns when a library is configured to create any class named in the input, such as Jackson's polymorphic "default typing" with broad base types. That has led to the same kind of gadget-chain exploits. Keep polymorphic typing restricted to an allow-list of your own classes.
Should I use serialization for deep copies? Only as a quick solution for occasional use, or in tests. A copy constructor, a static factory or a record's immutable design is faster, type-safe and does not require every class in the graph to be serializable.
API reference
| API | Purpose |
|---|---|
Object readResolve() | replace the object just read |
Object writeReplace() | replace the object about to be written |
static final long serialVersionUID | declare the class version |
serialver [-classpath p] class... | print a class's computed or declared UID |
ObjectInputStream.registerValidation(obj, priority) | schedule a validateObject callback after the graph is read |
ObjectInputValidation.validateObject() | check cross-object invariants, throw InvalidObjectException |
ObjectInputStream.setObjectInputFilter(filter) | filter for this stream, set before the first read |
ObjectInputFilter.Config.createFilter(pattern) | build a filter from a pattern string |
ObjectInputFilter.Config.setSerialFilter(filter) | process-wide default filter |
ObjectInputFilter.Config.setSerialFilterFactory(f) | pick a filter per stream (Java 17) |
ObjectInputFilter.FilterInfo | serialClass(), arrayLength(), depth(), references(), streamBytes() |
-Djdk.serialFilter=... / -Djdk.serialFilterFactory=... | configure filters without code changes |
Summary
readResolveswaps a deserialized object for another one. It fixes identity for pre-enum constant classes, but enums do it automatically.writeReplaceplus a proxy whosereadResolvecalls the real constructor makes every deserialized object pass the normal checks.- Declare
serialVersionUIDin any class whose serialized form must outlive a build. Useserialverto recover the UID of old versions. - Fields are matched by name: extra stream fields are skipped, missing ones get defaults, and type changes are errors.
- Validate in
readObject, or withObjectInputValidationfor checks that need the whole graph. - Deserializing untrusted data can run attacker-chosen code. Avoid it, authenticate the data, and restrict classes and sizes with filters.
- Serialization can deep-copy object graphs, slowly, and not every cyclic graph survives.
Practice Questions
Why does an enum-based singleton survive deserialization while a class with a private constructor and a static INSTANCE field doesn't?
Deserialization never calls the constructor, so it simply creates a second instance of the class. Enum constants are written by name and read back with valueOf, which returns the existing constant. For the class-based singleton you'd have to add a readResolve that returns INSTANCE, and make all instance fields transient.
Version 1 of a class had no serialVersionUID, and users have files. You now add a field. What do you do so that the old files stay readable?
Run serialver on the version 1 class to get its computed UID, and declare private static final long serialVersionUID with exactly that value in the new version. The new field will be null or zero when old files are read, so set a sensible default in readObject if that matters.
Which change breaks compatibility even when serialVersionUID is kept: renaming a method, adding a field, or changing a field from int to long?
Changing a field from int to long. Fields are matched by name and their types must agree exactly, so the stream throws InvalidClassException: incompatible types for field. Methods aren't part of the stream at all, and an added field just gets its default value.
What does the filter pattern com.example.dto.*;java.base/*;maxarray=10000;!* accept?
Classes in the package com.example.dto (not its subpackages) and classes from the java.base module, with no array longer than 10,000 elements. The trailing !* rejects every other class. Patterns are tried in order and the first match decides.
What is the serialization proxy pattern, and what problem does it solve?
The class's writeReplace returns a small proxy that holds the logical state. The proxy's readResolve builds the real object through its public constructor or factory, and the real class's readObject throws, so streams that try to bypass the proxy are rejected. Every deserialized instance therefore passes through the same validation as normally constructed ones. Fields can stay final, and the internal representation can change without affecting the stream.
Previous: Customizing Java Serialization: transient, readObject, writeObject and Externalizable
Next: Java Regular Expressions: Syntax, Character Classes and Quantifiers
Related reading
- Customizing Java Serialization: transient, readObject, writeObject and Externalizable
- The Java Serialization File Format: Handles, Class Descriptors and Fingerprints
- Java Object Serialization: Saving and Loading Objects
- Java File Locking: FileLock, Shared and Exclusive Locks
- Java NIO Buffers: Capacity, Position, Limit, flip and compact

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.