4.3. Using readObject and writeObject

If a class wishes to add some custom code that runs when an object is read from serialization, it can implement the readObject method:

private void readObject(ObjectInputStream stream)
             throws IOException, ClassNotFoundException

Before it reads an object's state from the stream, ObjectInputStream uses reflection to check to see if the object's class implements readObject. If it does, ObjectInputStream simply calls readObject instead of executing normal deserialization.

When you implement readObject, you normally do two things:

1.
Call back to ObjectInputStream and ask it to read the fields as in normal serialization.
2.
Execute any custom steps that you wish to add to the deserialization process.

Listing ...

Get Component Development for the Java™ Platform now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.