Customizing Java Serialization: transient, readObject, writeObject and Externalizable
Control what Java serialization saves: transient fields, private writeObject/readObject hooks with defaultWriteObject, serialPersistentFields with PutField/GetField, Externalizable with its public no-arg constructor, and how records are rebuilt through their canonical constructor.
kvi5hnuCode Sprout team member11 min readOn this page
Default serialization writes every non-static field of every serializable class in the object's hierarchy. That's often right, but not always. Some fields shouldn't be saved at all. Some hold objects that can't be serialized. Some classes need a compact or stable format of their own. This article covers the tools for each case, from the lightest (transient) to the heaviest (Externalizable), and ends with records, which take a different and safer route.
transient fields
Mark a field transient and serialization skips it. Typical candidates:
- references to things that make no sense in another process or at another time: open files, sockets, database connections, threads, locks
- caches and derived values that are cheaper to recompute than to store
- fields whose type isn't serializable
When the object is read back, a transient field has its default value: null, 0 or false. Field initializers and constructors of the serializable class don't run during deserialization (only the no-argument constructor of the first non-serializable superclass runs, as article 32 explained). So transient StringBuilder log = new StringBuilder() comes back as null, not as an empty builder. If the field needs a value, restore it in readObject.
writeObject and readObject
A serializable class can take over the writing and reading of its own fields by declaring these two methods, with exactly these signatures:
@Serial
private void writeObject(ObjectOutputStream out) throws IOException
@Serial
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
They aren't part of any interface. The serialization machinery finds them by reflection, so they must be private and have the exact parameter and exception types. The @Serial annotation (Java 14) documents that a member belongs to serialization. Since JDK 18, javac -Xlint:serial checks the declarations of serialization methods and fields in serializable classes. For example, it warns "serialization-related method writeObject not declared private" if you make one public. A misspelled method name is still silently ignored, so test the round trip.
Each method handles only the fields of its own class. Superclass state is written by the superclass (by default or by its own methods), and the class descriptor is written as usual. Inside these methods:
out.defaultWriteObject()writes the class's non-transient fields the normal way, andin.defaultReadObject()reads them back. Call them first, so the format can evolve: a later version of the class can add fields and still read old data.- After that, write any extra data with the
DataOutputmethods (writeInt,writeDouble,writeUTF,writeObjectand so on). Read it back in the same order.
The standard example is a field whose type isn't serializable. Make it transient, then save the parts that matter yourself:
private transient Point point;
@Serial
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeDouble(point.x);
out.writeDouble(point.y);
}
@Serial
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
point = new Point(in.readDouble(), in.readDouble());
}
The JDK uses the same technique widely. HashMap and HashSet don't save their bucket arrays. They write the capacity, load factor, size and the entries, and readObject rebuilds a fresh table, because the bucket layout depends on hash codes that may differ in another JVM. ArrayList writes only the used part of its backing array.
There's also readObjectNoData(), which is called when the stream holds an object of a subclass but no data for this class. That happens when this class was added as a superclass after the stream was written. It lets the class put its fields in a valid state.
serialPersistentFields: a stable wire layout
Sometimes the stream format must stay fixed while the class changes. A class can declare the fields that appear in the stream, independently of its real fields:
@Serial
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("fahrenheit", double.class)
};
It must be private static final. In writeObject, call out.putFields() to get an ObjectOutputStream.PutField, put each declared value, then call out.writeFields(). In readObject, in.readFields() returns an ObjectInputStream.GetField. Its get(name, defaultValue) returns the stored value, or the default when the stream doesn't contain that field, and defaulted(name) tells you which case happened. The JDK uses this for classes like BigInteger, whose internal fields changed long ago while its serialized form stayed the same.
Externalizable: complete control
A class that implements java.io.Externalizable takes over its whole serialized form:
public void writeExternal(ObjectOutput out) throws IOException;
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;
The differences from writeObject/readObject are significant:
- The stream records only the class descriptor (flag
SC_EXTERNALIZABLE) and then whateverwriteExternalwrites. No field descriptors are written, and superclass state isn't saved automatically.writeExternalis responsible for everything, including superclass fields. - To read, the stream calls the class's public no-argument constructor and then
readExternal. Without such a constructor you getInvalidClassException: no valid constructor. A nested externalizable class must bestatic, because an inner class's constructors take a hidden outer-instance parameter, so it has no real no-argument constructor. The class itself doesn't have to be public, only its no-argument constructor. - These are interface methods, so they're
publicand annotated@Override, not@Serial. Being public,readExternalcan be called by anyone on an existing object to overwrite its state. Fields can't befinaleither, sincereadExternalassigns them after construction.
Use Externalizable when you need a compact format or exact control over the bytes, and you're willing to handle versioning by hand.
Records
Records are serialized differently from ordinary classes, and the difference is entirely good:
- Only the record components are written, as named field values.
writeObject,readObject,readObjectNoData,writeExternal,readExternalandserialPersistentFieldsare ignored for records. - On reading, the stream collects the component values by name and calls the canonical constructor. Validation in the constructor therefore runs on deserialized data too, so a crafted stream can't produce a record that breaks its invariants.
- A missing component in the stream gets its default value, and an unknown one is ignored. This makes adding or removing components reasonably tolerant.
- As article 33 noted, a record's
serialVersionUIDis 0 unless declared, and it isn't checked. writeReplaceandreadResolve(article 35) still work.
If you're designing a new class whose serialized form matters, a record is the simplest and safest choice.
The program
The demo shows each technique in turn. It uses an in-memory round trip (write to a byte array, read back) to keep things short.
import java.io.*;
import java.util.*;
public class Solution {
// A class we don't control and that isn't serializable
static final class Point {
final double x, y;
Point(double x, double y) { this.x = x; this.y = y; }
@Override public String toString() { return "(" + x + ", " + y + ")"; }
}
// 1. transient fields plus writeObject/readObject
static class LabeledPoint implements Serializable {
@Serial private static final long serialVersionUID = 1L;
private final String label;
private transient Point point; // not serializable: we write it ourselves
private transient int cachedHash; // a cache: recompute instead of storing
LabeledPoint(String label, double x, double y) {
this.label = label;
this.point = new Point(x, y);
this.cachedHash = Objects.hash(label, x, y);
}
@Serial
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject(); // writes label
out.writeDouble(point.x);
out.writeDouble(point.y);
}
@Serial
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject(); // reads label
double x = in.readDouble();
double y = in.readDouble();
point = new Point(x, y);
cachedHash = Objects.hash(label, x, y);
}
@Override public String toString() { return label + point + " hash ok: " + (cachedHash == Objects.hash(label, point.x, point.y)); }
}
// 2. transient without custom methods: the field comes back as its default
static class Session implements Serializable {
@Serial private static final long serialVersionUID = 1L;
String user = "ada";
transient StringBuilder log = new StringBuilder("started");
}
// 3. serialPersistentFields: keep an old wire layout after the class changed
static class Temperature implements Serializable {
@Serial private static final long serialVersionUID = 1L;
@Serial
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("fahrenheit", double.class) // the field name old files used
};
private transient double celsius; // the field the class uses now
Temperature(double celsius) { this.celsius = celsius; }
@Serial
private void writeObject(ObjectOutputStream out) throws IOException {
ObjectOutputStream.PutField fields = out.putFields();
fields.put("fahrenheit", celsius * 9 / 5 + 32);
out.writeFields();
}
@Serial
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
ObjectInputStream.GetField fields = in.readFields();
celsius = (fields.get("fahrenheit", 32.0) - 32) * 5 / 9;
}
}
// 4. Externalizable: the class writes everything itself
public static class Pixel implements Externalizable {
@Serial private static final long serialVersionUID = 1L;
private int x, y;
private String color;
public Pixel() { System.out.println(" Pixel() no-arg constructor called"); }
Pixel(int x, int y, String color) { this.x = x; this.y = y; this.color = color; }
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeShort(x);
out.writeShort(y);
out.writeUTF(color);
}
@Override
public void readExternal(ObjectInput in) throws IOException {
x = in.readShort();
y = in.readShort();
color = in.readUTF();
}
@Override public String toString() { return "Pixel[" + x + "," + y + "," + color + "]"; }
}
// 5. records: deserialized through the canonical constructor
record Range(int low, int high) implements Serializable {
Range {
System.out.println(" Range constructor(" + low + ", " + high + ")");
if (low > high) throw new IllegalArgumentException("low > high");
}
}
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 {
try (var in = new ObjectInputStream(new ByteArrayInputStream(data))) {
return in.readObject();
}
}
static Object roundTrip(Object obj) throws IOException, ClassNotFoundException {
return load(save(obj));
}
public static void main(String[] args) throws Exception {
System.out.println("1. " + roundTrip(new LabeledPoint("home", 1.5, -2)));
var s = (Session) roundTrip(new Session());
System.out.println("2. user=" + s.user + ", log=" + s.log);
var t = (Temperature) roundTrip(new Temperature(100));
System.out.println("3. celsius=" + t.celsius + ", stream fields "
+ Arrays.toString(ObjectStreamClass.lookup(Temperature.class).getFields()));
System.out.println("4. writing a Pixel");
byte[] pixel = save(new Pixel(3, 4, "teal"));
System.out.println(" " + load(pixel) + ", " + pixel.length + " bytes");
System.out.println("5. writing a Range");
byte[] range = save(new Range(1, 9));
System.out.println(" " + load(range));
// Tamper with the stream: swap the two int values (1 and 9) at the end
int n = range.length;
byte[] evil = range.clone();
System.arraycopy(range, n - 4, evil, n - 8, 4);
System.arraycopy(range, n - 8, evil, n - 4, 4);
try {
load(evil);
} catch (InvalidObjectException e) {
System.out.println(" tampered stream rejected: " + e.getMessage());
}
}
}
1. home(1.5, -2.0) hash ok: true
2. user=ada, log=null
3. celsius=100.0, stream fields [D fahrenheit]
4. writing a Pixel
Pixel() no-arg constructor called
Pixel[3,4,teal], 48 bytes
5. writing a Range
Range constructor(1, 9)
Range constructor(1, 9)
Range[low=1, high=9]
Range constructor(9, 1)
tampered stream rejected: low > high
What to notice:
LabeledPointsurvives althoughPointisn't serializable, and its transient cache is recomputed.- The transient
logcomes back asnull. The field initializer didn't run. - The stream's only field is
fahrenheit, while the object usescelsius. - Reading a
Pixelcalls its public no-argument constructor. - The
Rangeconstructor runs when the record is read back, and a stream edited to swaplowandhighis rejected withInvalidObjectExceptionthat wraps the constructor's message. In the stream,highcomes beforelow, because fields are sorted by name.
Common questions
Is Java's transient the same as JPA's @Transient?
No. The transient keyword excludes a field from Java serialization. The @Transient annotation in JPA (Jakarta Persistence) excludes it from being stored in the database. JPA also ignores fields marked with the transient keyword, so marking a field with the keyword hides it from both, while the annotation hides it only from the database.
Can a record component be transient?
No. Record components cannot have modifiers, and a record cannot declare additional instance fields. Every component is part of the serialized form. If a record holds something that should not be saved, it probably should not be a component.
Why must writeObject and readObject be private, when they are called from outside?
The serialization machinery calls them through reflection, bypassing access control, so they don't need to be visible. Making them private keeps them out of the class's API and makes sure each class in the hierarchy handles only its own fields, not a subclass's.
Externalizable or custom writeObject/readObject?
Prefer writeObject/readObject with defaultWriteObject first. It keeps the automatic handling of superclasses and versioning, and you only add what is special. Externalizable is for rare cases where every byte counts or the format must match something external, and it costs you a public constructor, a public readExternal and all versioning work.
How do I restore a transient cache after deserialization?
Recompute it at the end of readObject, or make the field lazily initialized: leave it null and compute it on first use. The lazy approach also works for objects created normally.
API reference
| API | Purpose |
|---|---|
transient | exclude a field from default serialization |
@Serial (java.io) | mark serialization-related members, checked by javac -Xlint:serial |
private void writeObject(ObjectOutputStream) | write this class's state yourself |
private void readObject(ObjectInputStream) | read this class's state yourself |
private void readObjectNoData() | initialize state when the stream has none for this class |
ObjectOutputStream.defaultWriteObject() | write non-transient fields of the current class |
ObjectInputStream.defaultReadObject() | read non-transient fields of the current class |
private static final ObjectStreamField[] serialPersistentFields | declare the stream's fields explicitly |
ObjectOutputStream.putFields() / writeFields() | set and write declared field values |
ObjectInputStream.readFields() | read field values into a GetField |
GetField.get(name, default) / defaulted(name) | fetch a value, or detect that it was missing |
Externalizable.writeExternal(ObjectOutput) | write the whole object state |
Externalizable.readExternal(ObjectInput) | read the whole state after the no-arg constructor ran |
InvalidObjectException | throw from readObject when the data violates invariants |
Summary
transientfields aren't saved and come back asnull,0orfalse. Initializers don't run on deserialization.- Private
writeObject/readObjectmethods customize one class's part of the stream. CalldefaultWriteObject/defaultReadObjectfirst, then write and read extra data in the same order. - Treat
readObjectas a constructor: validate, copy defensively, avoid overridable calls. serialPersistentFieldswithPutField/GetFielddecouples the stream layout from the actual fields.Externalizablehands the entire format to the class. It needs a public no-arg constructor, its methods are public, and the class handles superclass state and versioning.- Records are rebuilt through the canonical constructor, so their validation always runs. Custom serialization methods are ignored for them.
Practice Questions
A class has the field transient List\<String\> tags = new ArrayList\<\>();. What is tags after deserialization, and how do you fix it?
It's null. Deserialization doesn't run field initializers or constructors of serializable classes. Either drop transient if the list should be saved, or add a readObject that calls defaultReadObject() and then sets tags = new ArrayList<>().
Why must writeObject and readObject be private, and what happens if you misspell one?
The serialization machinery looks them up by reflection with exact names and signatures, and the specification requires them to be private so that they belong to exactly one class in the hierarchy. A misspelled method, say readObjekt, is just an ordinary unused method, so default serialization runs silently. -Xlint:serial catches wrong modifiers or signatures on correctly named methods, but not a wrong name. A round-trip test catches both.
What does defaultReadObject do, and why should it be called even when every field is transient?
It reads the current class's non-transient fields from the stream. If every field is transient it reads nothing today, but calling it keeps the format extensible. A later version can add non-transient fields, and older or newer readers still find the data where they expect it.
Name three differences between implementing Externalizable and writing readObject/writeObject.
Externalizable writes the whole object, including superclass state, while readObject/writeObject cover only one class. Reading an externalizable object calls its public no-arg constructor, while ordinary serialization calls none of the serializable classes' constructors. And readExternal/writeExternal are public interface methods, while the other pair is private. A further difference: no field descriptors are written for externalizable classes, so there's no automatic versioning.
An attacker edits a stream so a record Range(int low, int high) gets low = 9 and high = 1. The compact constructor rejects low > high. What happens on deserialization?
Records are deserialized by calling the canonical constructor with the stream's values, so the check runs and throws. ObjectInputStream reports it as an InvalidObjectException, and no Range is ever created. An ordinary class with the same check in its constructor would get no such protection unless it repeated the check in readObject.
Previous: The Java Serialization File Format: Handles, Class Descriptors and Fingerprints
Next: Java Serialization: readResolve, writeReplace, Versioning and Security
Related reading
- 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
- Java Memory-Mapped Files: FileChannel.map and Performance

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.