Writing Additional Data in writeObject
What you'll learn: How to serialize extra data beyond your class's instance fields by writing primitive values and objects directly into the serialization stream.
The Core Idea
Sometimes default serialization isn't enough. Maybe you need to serialize a derived value, encrypt data before writing it, or store a field in a different format. The writeObject method lets you take control by writing additional data using methods like writeInt(), writeUTF(), writeDouble(), and others from ObjectOutputStream.
After calling defaultWriteObject() to handle standard fields, you can append extra data to the stream. Just remember: whatever you write in writeObject(), you must read back in the same order in readObject().
How It Works
Think of the serialization stream as a tape recorder. defaultWriteObject() records all your regular fields automatically. Then you can manually add extra recordings—a number here, a string there—using the various write*() methods. During deserialization, you'll rewind and play back everything in the exact same sequence.
Example pattern:
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject(); // Write normal fields first
// Now write additional custom data
out.writeInt(someCalculatedValue);
out.writeUTF(someTransformedString);
out.writeDouble(someMetric);
}
You must read these back in readObject() in the same order:
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject(); // Read normal fields first
int value = in.readInt();
String str = in.readUTF();
double metric = in.readDouble();
}
When to Use This
This technique shines when you need to serialize computed state, version markers, or reformatted data that isn't stored directly in your fields.
Key Takeaway: Use ObjectOutputStream's writeInt(), writeUTF(), and similar methods in writeObject() to append custom data beyond default fields—just ensure you read them back in the same order during deserialization.