Skip to content
Tutorials Center
My learning

Topics

Lesson 117 of 201 ยท Input and Output

Serialization

Learn Java serialization - Serializable, ObjectOutputStream and ObjectInputStream, transient fields, serialVersionUID, custom writeObject, records, filters and safer alternatives.

Serialization turns an object in memory into a sequence of bytes, and deserialization turns those bytes back into an equivalent object. Once an object is bytes, you can save it in a file, put it in a cache, or send it to another program over the network. Java has had a built-in mechanism for this since version 1.1: mark a class Serializable, hand an object to an ObjectOutputStream, and Java writes the object, every object it refers to, and enough type information to rebuild them all.

It looks magical, and in a way it is: deserialization creates objects without calling their constructors. That magic is also why built-in serialization has become one of the most criticized parts of Java. Its own designers have called it a mistake, and it has been behind many serious security vulnerabilities. You still need to understand it, because you'll meet it in existing code, in caches and session stores, and in job interviews. This lesson teaches how it works, its rules and traps, how to make it safer, and what to use instead in new code.

Your first serialized object

A class opts in by implementing the marker interface java.io.Serializable, which has no methods. ObjectOutputStream.writeObject serializes, ObjectInputStream.readObject deserializes. The examples write to a byte array in memory, but a file stream works the same way:

Java Round-tripping an object through bytes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Several things happened that are worth noticing:

  • The List inside the customer was serialized too. Serialization follows every reference and writes the whole object graph. Every object in it must be serializable; ArrayList, String and most JDK value classes are.
  • The constructor ran once, for the original. Deserialization allocated the copy and filled in its fields directly, even the final ones, bypassing the constructor and any validation in it.
  • The result is a deep copy: a separate object with its own list, so changing the copy leaves the original alone.
  • Every stream starts with the "magic number" aced, followed by a version. You'll recognize it in hex dumps and network captures.
  • readObject returns Object, so you must cast, and it throws ClassNotFoundException if the class isn't available on the reading side.
  • The classes here are static nested classes. A non-static inner class keeps a hidden reference to its outer object, which would then have to be serialized too (Nested Classes).

Which fields are saved: transient and static

By default, every non-static, non-transient field is written. Mark a field transient to leave it out: after deserialization it has its type's default value (null, 0, false). Use it for data that's secret, derived, or meaningless in another process, like a cache, a password or an open connection. Static fields belong to the class, not the object, so they're never serialized.

Java transient fields, static fields and shared references

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The password and the cached score came back empty, the static counter shows the constructor never ran for the copy, and the last line demonstrates another property of serialization: if two references point to the same object, the stream writes it once and both references point to one shared object after reading. Cycles (an object that refers back to itself, directly or indirectly) are handled the same way.

NotSerializableException

If any object in the graph isn't serializable, writing fails with NotSerializableException, naming the guilty class. It's a common surprise when a serializable class gains a field of a non-serializable type:

Java A non-serializable field breaks the whole graph

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

After deserializing a FixedOrder, logger is null because field initializers don't run either (they're part of the constructor). If the object needs the logger, recreate it in a custom readObject method, shown next.

serialVersionUID and class evolution

Serialized bytes often outlive the program that wrote them: a file saved by version 1 of your app is read by version 2. Each serializable class has a version number, serialVersionUID, which is written into the stream. When reading, Java compares it with the current class's value; if they differ, readObject throws InvalidClassException ("local class incompatible").

If you don't declare serialVersionUID, Java computes one from the class's structure: its name, fields, methods and interfaces. Then almost any change, even adding a harmless method, changes the computed number, and every previously saved object becomes unreadable. The compiler can warn you about this (javac -Xlint:serial). So always declare it:

Java
private static final long serialVersionUID = 1L;

With a fixed value, Java tolerates compatible changes: added fields get default values when old data is read, and fields that no longer exist in the class are ignored. Changing a field's type, or turning a class hierarchy around, is incompatible. Change the number deliberately when you want old data rejected.

Custom serialization: writeObject and readObject

A class can control its own format by declaring two private methods with exact signatures. Java finds and calls them through reflection, which is unusual but how the mechanism was designed:

Java Validating and rebuilding state in readObject

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The tampering demo makes the key point: bytes are not trustworthy input. Because the constructor doesn't run, an attacker who edits a serialized file can create objects your constructor would never allow. Any invariant the constructor enforces must be checked again in readObject. The @Serial annotation (Java 14) marks serialization methods and fields so the compiler can check their signatures; it has no effect at run time.

Other hooks you may meet:

  • writeReplace() and readResolve() substitute a different object when writing or reading. readResolve is the classic way to keep a singleton a singleton after deserialization.
  • Externalizable is an interface with writeExternal/readExternal for full manual control; it calls the public no-argument constructor first.
  • Enums are serialized by name and always deserialize to the existing constant, which is why an enum is the safest singleton (Enums).

Records serialize safely

Records (Records) got special treatment in serialization: they're written as their components, and when read back, the canonical constructor is called. That means a compact constructor's validation runs during deserialization too, closing the hole shown above. If a data class needs to be serializable, make it a record whenever you can:

Java Records go through their constructor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The constructor message appears twice: once when creating and once when reading. Records can't use writeObject/readObject or serialPersistentFields customization; whatever the constructor allows is what can be deserialized.

The security problem and deserialization filters

Never deserialize data from an untrusted source (a network request, an uploaded file, a cookie) with plain ObjectInputStream. An attacker can craft bytes that create objects of any serializable class on your classpath, in any combination. Clever chains of ordinary library classes ("gadget chains") have been used to execute arbitrary code on servers, which is how several large breaches happened.

If you must read serialized data that might be tampered with, Java 9 added deserialization filters (ObjectInputFilter). A filter decides, for every class in the stream, whether it may be created, and can also limit graph depth, array sizes and total bytes. The pattern syntax lists allowed classes or packages and ends with !* to reject everything else:

Java An allowlist with ObjectInputFilter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The filter allowed the list and the points but rejected Unexpected before creating it. (java.lang.Object is listed because ArrayList stores its elements in an Object[].) You can also set a JVM-wide filter with the jdk.serialFilter system property, and Java 17 added filter factories for per-context rules. Filters reduce the risk; they don't make deserializing untrusted data a good idea.

Alternatives for new code

Built-in serialization ties your data format to your Java class internals, only works between Java programs, produces bulky output and carries the security risks above. For new code, pick a format designed for data:

Need Better choice
Exchanging data with other systems, web APIs, config JSON with a library such as Jackson (covered in Advanced Java)
Compact, fast, versioned binary messages Protocol Buffers, Avro or similar schema-based formats
Simple fixed binary layout DataOutputStream/DataInputStream (Byte and Character Streams)
Human-editable settings Properties files (Properties Files and Configuration)
Storing many records and querying them A database (JDBC, also in Advanced Java)
A deep copy of an object A copy constructor or factory (Copying Objects)

These formats only create the types you ask for, keep working when your classes are refactored, and can be read by programs in any language. Built-in serialization remains acceptable for short-lived data between trusted Java processes that you control on both ends, such as some caches.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A Serializable class has a constructor that prints "created". You serialize one object and deserialize it twice. How many times is "created" printed?

    Deserialization of a regular Serializable class doesn't call its constructor (records are the exception), so only the original creation prints.
  2. 2. A serializable class has transient int visits = 10;. What is visits after deserialization?

    transient fields aren't written, and field initializers don't run during deserialization, so the field gets the default value 0.
  3. 3. Why should you always declare serialVersionUID?

    The computed ID changes with almost any modification to the class, causing InvalidClassException when reading data written by an older version.
  4. 4. What happens when a record is deserialized?

    Records are deserialized by passing the stored components to the canonical constructor, which makes them much safer than ordinary classes.
  5. 5. Your server receives serialized Java objects from users' browsers. What's the right fix?

    Deserializing untrusted bytes lets attackers instantiate arbitrary classes. Don't do it; if you can't avoid it yet, a strict allowlist filter limits what can be created.

Summary

  • Implement Serializable and use ObjectOutputStream.writeObject / ObjectInputStream.readObject to turn object graphs into bytes and back; shared references and cycles are preserved.
  • Deserialization bypasses constructors and field initializers; transient and static fields aren't stored.
  • Every object in the graph must be serializable, or writing fails with NotSerializableException.
  • Always declare private static final long serialVersionUID; mismatches cause InvalidClassException.
  • Private writeObject/readObject customize the format; re-check invariants in readObject. Records are rebuilt through their canonical constructor.
  • Never deserialize untrusted data; use ObjectInputFilter allowlists if you must, and prefer JSON, schema-based formats or databases in new code.

Next: Character Sets and Encoding, where you'll see exactly how text becomes bytes and how to avoid garbled characters.