Serialization
Serialization is the process of converting an object to a byte stream so it can be persisted, cached or transmitted. Java has a built-in serialisation mechanism via the Serializable marker interface and ObjectOutputStream, but it is a security liability and largely replaced by JSON/Protobuf in modern code.
Built-in Java serialization
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
}
// Write:
try (var out = new ObjectOutputStream(new FileOutputStream("user.bin"))) {
out.writeObject(new User("Ada", 36));
}
// Read:
try (var in = new ObjectInputStream(new FileInputStream("user.bin"))) {
User u = (User) in.readObject();
}
Why Java serialization is dangerous
Deserializing untrusted byte streams can execute arbitrary code via gadget chains β the cause of many CVEs over the last decade. The JEP 290 serialization filter helps, but the safest rule is: never deserialize data from an untrusted source with ObjectInputStream.
Modern alternatives
- JSON with Jackson or Gson β human-readable, language-agnostic, no code execution risk.
- Protocol Buffers β compact binary format with strict schema.
- Avro β common in Kafka and data pipelines.
- java.io.Externalizable β gives manual control over the bytes written; still uses ObjectInputStream.
Serialization is being replaced
JEP 154 plans to eventually remove built-in serialization from Java entirely. Don't build anything new on top of it.