Records and validation while reading
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)An invariant is a rule that must always be true for an object, such as "marks are between 0 and 100" or "balance is never negative". Constructors usually check these rules, but deserialization can create objects without calling the constructor, so the rules need extra care.
Records are rebuilt through their constructor
A serializable record is a record that implements Serializable: record Marks(String student, int marks) implements Serializable {}. Records (Java 16+) are serialized in a special way: Java saves the value of each component, and on reading it calls the record's canonical constructor with those values.
Example 1 · A record runs its constructor when it is read
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.ObjectStreamClass;import java.io.Serializable;
record Marks(String student, int marks) implements Serializable { Marks { System.out.println(" constructor checks " + student + ", " + marks); if (marks < 0 || marks > 100) { throw new IllegalArgumentException("marks must be 0-100, got " + marks); } }}
public class RecordRebuildDemo { public static void main(String[] args) throws IOException, ClassNotFoundException { System.out.println("Creating:"); Marks m = new Marks("Aditi", 88);
ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try (ObjectOutputStream out = new ObjectOutputStream(buffer)) { out.writeObject(m); }
System.out.println("Reading:"); try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()))) { Marks back = (Marks) in.readObject(); System.out.println("Loaded " + back); System.out.println("Equal to the original? " + back.equals(m)); } System.out.println("Record version number: " + ObjectStreamClass.lookup(Marks.class).getSerialVersionUID()); }}Creating: constructor checks Aditi, 88 Reading: constructor checks Aditi, 88 Loaded Marks[student=Aditi, marks=88] Equal to the original? true Record version number: 0
What this code does
- "constructor checks" prints twice: once for
new Marks(...)and once while reading, because Java rebuilds a record with its canonical constructor. - The loaded record is equal to the original (records compare their components), but it is a new object.
- A record's
serialVersionUIDis 0 unless declared, and Java does not compare it when reading records.
Example 2 · A new record component gets a default through the constructor
import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.Serializable;import java.util.Base64;
// Version 2 of the record: the year component is newrecord Student(String name, int roll, int year) implements Serializable { Student { if (year == 0) { year = 1; // old data has no year: use a sensible default } if (year < 1 || year > 4) { throw new IllegalArgumentException("year must be 1-4, got " + year); } }}
public class RecordEvolveDemo { // Saved earlier by version 1: record Student(String name, int roll) static final String SAVED_BY_V1 = "rO0ABXNyAAdTdHVkZW50AAAAAAAAAAACAAJJAARyb2xsTAAEbmFtZXQAEkxqYXZhL2xhbmcvU3RyaW5nO3hwAAAADHQABVByaXlh";
public static void main(String[] args) throws IOException, ClassNotFoundException { byte[] bytes = Base64.getDecoder().decode(SAVED_BY_V1); try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) { Student s = (Student) in.readObject(); System.out.println(s); } }}Student[name=Priya, roll=12, year=1]
What this code does
SAVED_BY_V1was written byrecord Student(String name, int roll). The record now has a third component,year.- The old data has no
year, so Java passes 0 to the constructor, and the compact constructor turns it into 1. - One constructor now handles new objects, old data and checks, with no
readObjectneeded.
So a record is always built by its own constructor, both when you write new Marks(...) and when it is read from bytes. Whatever the constructor checks or fixes also happens on reading. Records also make class changes easier. Components are matched by name, a missing component gets the default value (0, false, null) as the constructor argument, and the serialVersionUID check is skipped for records (their value is 0 unless you declare one).
Two rules for serializable records:
- You cannot customise a record's serialization with
writeObjectorreadObject; Java ignores those methods in a record. - Every component's type must be serializable, just like the fields of a class.
Validation in a compact constructor still runs
A compact constructor is the short record constructor with no parameter list, Marks { ... }, where you check or adjust the component values. Because deserialization calls it, a check such as if (marks > 100) throw ... also protects data read from a file.
Example 3 · Tampered marks are rejected by the compact constructor
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InvalidObjectException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import java.nio.ByteBuffer;
record Marks(String student, int marks) implements Serializable { Marks { if (marks < 0 || marks > 100) { throw new IllegalArgumentException("marks must be 0-100, got " + marks); } }}
public class TamperedRecordDemo { // Finds the int oldValue in the bytes and writes newValue there, like someone editing the file static void replaceInt(byte[] data, int oldValue, int newValue) { ByteBuffer buf = ByteBuffer.wrap(data); // same byte order as ObjectOutputStream for (int i = 0; i + 4 <= data.length; i++) { if (buf.getInt(i) == oldValue) { buf.putInt(i, newValue); return; } } }
public static void main(String[] args) throws IOException, ClassNotFoundException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try (ObjectOutputStream out = new ObjectOutputStream(buffer)) { out.writeObject(new Marks("Aditi", 88)); } byte[] bytes = buffer.toByteArray(); replaceInt(bytes, 88, 250); // the file now says 250 marks
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) { Marks back = (Marks) in.readObject(); System.out.println("Loaded " + back); } catch (InvalidObjectException e) { System.out.println("Rejected: " + e.getMessage()); System.out.println("Cause: " + e.getCause()); } }}Rejected: marks must be 0-100, got 250 Cause: java.lang.IllegalArgumentException: marks must be 0-100, got 250
What this code does
replaceIntchanges the saved 88 into 250, like someone editing the file.- Reading calls the compact constructor with 250, the check throws, and
readObjectreports it asInvalidObjectExceptionwith the same message. getCause()keeps the originalIllegalArgumentException, which helps when you log the problem.
When the constructor throws during reading, readObject throws InvalidObjectException. Its message is the constructor's message, and getCause() is the original IllegalArgumentException. The examples simulate an edited file with a small helper, replaceInt. It finds a saved int in the bytes and overwrites it, for example 88 becomes 250. ByteBuffer (from java.nio) reads and writes an int at any position in a byte array.
Why plain classes can skip constructor checks
For a normal serializable class, Java does not run the class's constructor when reading. It creates an empty object (running only the no-argument constructor of the first non-serializable parent, usually Object) and then copies the saved values straight into the fields, even private final ones.
Example 4 · Mistake: a plain class accepts a negative balance
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import java.nio.ByteBuffer;
class Wallet implements Serializable { private static final long serialVersionUID = 1L; private final String owner; private final int balance;
Wallet(String owner, int balance) { if (balance < 0) { throw new IllegalArgumentException("balance cannot be negative"); } this.owner = owner; this.balance = balance; }
@Override public String toString() { return owner + ": Rs " + balance; }}
public class PlainClassHoleDemo { static void replaceInt(byte[] data, int oldValue, int newValue) { ByteBuffer buf = ByteBuffer.wrap(data); for (int i = 0; i + 4 <= data.length; i++) { if (buf.getInt(i) == oldValue) { buf.putInt(i, newValue); return; } } }
public static void main(String[] args) throws IOException, ClassNotFoundException { try { new Wallet("Kiran", -5000); } catch (IllegalArgumentException e) { System.out.println("Constructor: " + e.getMessage()); }
ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try (ObjectOutputStream out = new ObjectOutputStream(buffer)) { out.writeObject(new Wallet("Kiran", 5000)); } byte[] bytes = buffer.toByteArray(); replaceInt(bytes, 5000, -5000); // someone edits the saved file
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) { Wallet w = (Wallet) in.readObject(); System.out.println("Deserialized: " + w); } }}Constructor: balance cannot be negative Deserialized: Kiran: Rs -5000
What this code does
new Wallet("Kiran", -5000)is refused by the constructor.- The same value read from edited bytes is accepted: Java fills the
private finalfield directly and never runs the constructor's check. - The class looks safe in code review, which is what makes this hole easy to miss.
So the bytes decide the field values, not your constructor. If someone edits a saved file, or builds bytes by hand, they can create a Wallet with a negative balance that new Wallet(...) would never allow. This is not a rare trick: the bytes are just data, and anything that can change a file or a network message can change them.
readObject in a normal class for checks
A plain class gets the same safety from a validating readObject: private void readObject(ObjectInputStream in) that first calls in.defaultReadObject() and then checks every rule the constructor checks. If a rule fails, it throws InvalidObjectException, and the bad object never reaches your program.
Example 5 · A validating readObject closes the hole
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InvalidObjectException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serial;import java.io.Serializable;import java.nio.ByteBuffer;
class Wallet implements Serializable { @Serial private static final long serialVersionUID = 1L; private final String owner; private final int balance;
Wallet(String owner, int balance) { this.owner = owner; this.balance = balance; check(); }
private void check() { if (owner == null || owner.isBlank()) { throw new IllegalArgumentException("owner is missing"); } if (balance < 0) { throw new IllegalArgumentException("balance cannot be negative"); } }
@Serial private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); try { check(); // the same rules as the constructor } catch (IllegalArgumentException e) { throw new InvalidObjectException("Bad Wallet data: " + e.getMessage()); } }
@Override public String toString() { return owner + ": Rs " + balance; }}
public class ReadObjectCheckDemo { static void replaceInt(byte[] data, int oldValue, int newValue) { ByteBuffer buf = ByteBuffer.wrap(data); for (int i = 0; i + 4 <= data.length; i++) { if (buf.getInt(i) == oldValue) { buf.putInt(i, newValue); return; } } }
static void load(byte[] bytes) throws IOException, ClassNotFoundException { try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) { System.out.println("Loaded " + in.readObject()); } catch (InvalidObjectException e) { System.out.println("Rejected: " + e.getMessage()); } }
public static void main(String[] args) throws IOException, ClassNotFoundException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try (ObjectOutputStream out = new ObjectOutputStream(buffer)) { out.writeObject(new Wallet("Kiran", 5000)); } byte[] good = buffer.toByteArray(); byte[] bad = good.clone(); replaceInt(bad, 5000, -5000);
load(good); load(bad); }}Loaded Kiran: Rs 5000 Rejected: Bad Wallet data: balance cannot be negative
What this code does
readObjectreads the fields withdefaultReadObject(), then runscheck(), the same rules the constructor uses.- Good bytes load normally. The edited bytes fail with
InvalidObjectException("Bad Wallet data: ..."), so no badWalletis ever created. @SerialonreadObjectandserialVersionUIDasks the compiler to check their signatures.
In that method:
- Check every field, including combinations:
present <= total,fromnot equal toto. - Rebuild transient fields in the same method, after the checks.
- For data you own and control, prefer a record: the constructor does this for you.
Put the rules in one private method and call it from both the constructor and readObject, so the two can never drift apart. Mark readObject with @Serial so the compiler checks its signature.
Find the bug
Find the validation bug
Each snippet should reject bad marks when reading. Tap the wrong line, then check the fix.
Java must call this method when an object is read.
Round 1 of 3Next step
Check your understanding
12 quick questions