Video in progress
How do `record` classes differ from ordinary classes in Java serialization?
A record is created through its canonical constructor during deserialization, so the constructor's checks run and a stream can't bypass the invariant. Custom methods like readObject/writeObject are ignored, and serialVersionUID defaults to 0L and is not required to match.
📖 Answer
In an ordinary Serializable class, deserialization bypasses the constructor and fills the fields directly. So even if you check amount > 0 in the constructor, a crafted stream can create an object with a negative amount; to protect yourself you had to repeat the check in readObject.
With a record (Java 16, JEP 395) it is different:
record Payment(String id, long amount) implements Serializable {
Payment {
if (amount <= 0) throw new IllegalArgumentException("summa musbat bo'lsin");
Objects.requireNonNull(id);
}
}
The stream holds only the component names and values. When reading, the JVM finds the values by name and calls the canonical constructor. If the check fails, you get InvalidObjectException, and no half-created object comes out.
The rules that follow:
- a component missing from the stream is passed to the constructor with a default value (
null,0), and an extra field is dropped. Adding and removing components does not break compatibility; - if you don't write
serialVersionUIDit is0L, and for a record the UID match is not checked, so the "local class incompatible" error almost never occurs with records; writeObject,readObject,readObjectNoDataandserialPersistentFieldsare not taken into account.writeReplaceandreadResolvedo work;- renaming a component means "the field disappeared" for old data, so be careful.
If you still need Java serialization (a cache, old sessions), make the DTOs records: it is much safer and more stable.
Sign up to mark studied questions and save your progress.