Reading Additional Data in readObject
You'll learn how to restore custom data written by writeObject using matching read methods in the correct order.
The Mirror Image of Custom Writing
In the previous lesson, you learned to write extra data in writeObject using methods like writeInt() or writeUTF(). Now you need to read that data back during deserialization—and order matters absolutely.
Think of it like unpacking a suitcase you packed yourself. If you put shoes in first, then clothes, then toiletries, you must unpack in that exact sequence to find what you're looking for.
How to Read Custom Data
When implementing readObject, you read additional data using the ObjectInputStream methods that match what you wrote:
- If you wrote with
writeInt(), read withreadInt() - If you wrote with
writeUTF(), read withreadUTF() - If you wrote with
writeLong(), read withreadLong()
Critical: Read in the same order you wrote. If your writeObject wrote an int then a String, your readObject must read an int then a String.
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject(); // Read standard fields first
// Read custom data in SAME ORDER as written
this.timestamp = in.readLong();
this.sessionId = in.readUTF();
this.retryCount = in.readInt();
}
If the order is wrong, you'll get garbled data or exceptions—readInt() trying to interpret string bytes will fail spectacularly.
The Golden Rule
readObject must be the exact mirror of writeObject. Same methods, same sequence, same number of calls. Any mismatch breaks deserialization.
Key Takeaway: When reading additional data in readObject, use matching ObjectInputStream methods (readInt, readUTF, etc.) in the exact same order the data was written in writeObject.