Course contentsShow
← Java
Lesson 2141 of 2,87042. SerializationFree lesson

The readObject Method Signature

Understand the exact signature private void readObject(ObjectInputStream) and the IOException and ClassNotFoundException it must declare.

The readObject Method Signature

You'll learn the exact method signature required when customizing deserialization in Java.

Understanding the Signature

When you need custom logic during deserialization (complementing the writeObject method you learned previously), you must define a method called readObject with a very specific signature. Java's serialization mechanism uses reflection to discover and invoke this method, so getting the signature exactly right is crucial.

The required signature is:

private void readObject(ObjectInputStream in) 
    throws IOException, ClassNotFoundException

Breaking Down Each Part

Access Modifier: private

Like writeObject, this must be private. The serialization framework accesses it via reflection, not through normal inheritance or visibility rules.

Return Type: void

It doesn't return anything; it reconstructs the object's state in place.

Parameter: ObjectInputStream in

This stream provides access to the serialized data you wrote. You'll call methods like in.defaultReadObject() or in.readInt() on it.

Exception Declarations

You must declare both:

  • IOException: For stream-related problems during reading
  • ClassNotFoundException: Thrown when the stream contains an object whose class definition cannot be found

Think of It Like This

Imagine receiving a specially-packaged box (the stream). Your readObject method is the unpacking instructions that must warn about two problems: damaged packaging (IOException) or receiving an item you don't recognize (ClassNotFoundException).

Key Takeaway: The readObject signature must be exactly private void readObject(ObjectInputStream) throws IOException, ClassNotFoundException for Java's serialization to recognize and invoke it during deserialization.