Validating Object State in readObject
What You'll Learn
You'll learn how to protect your program from invalid objects by performing validation checks inside your custom readObject() method after deserialization.
Why Validation Matters After Deserialization
When you deserialize an object, the normal constructor is not called. This means your usual validation logic is bypassed. An attacker or corrupted stream could create an object with invalid field values that would never pass your constructor's checks.
Think of deserialization like a backdoor into your house—if you don't check who comes through, anything could sneak in.
How to Validate in readObject
After calling defaultReadObject() to restore your fields, immediately validate the object's state. If anything is invalid, throw an InvalidObjectException.
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject();
// Validate restored state
if (age < 0 || age > 150) {
throw new InvalidObjectException(
"Age must be between 0 and 150, got: " + age);
}
if (name == null || name.trim().isEmpty()) {
throw new InvalidObjectException(
"Name cannot be null or empty");
}
}
What to Check
Validate the same invariants you enforce in your constructor:
- Null checks for required fields
- Range checks for numeric values
- Consistency checks between related fields
- Any business rules your class depends on
This prevents your program from operating on corrupted or malicious objects that could cause crashes, security vulnerabilities, or data corruption.
Key Takeaway: Always validate your object's state in readObject() after defaultReadObject() to enforce invariants and prevent invalid objects from being created through deserialization.