Question

From the Serialization chapter of Effective Java:

If the class of an object being deserialized defines a readResolve method with the proper declaration, this method is invoked on the newly created object after it is deserialized.

The example provided in Effective Java is the following and it seems like the throws part is missing from what the Javadoc says is the correct format ie ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;

 // readResolve for instance control - you can do better!
        private Object readResolve () {
            // Return the one true Elvis and let the garbage collector
            // take care of the Elvis impersonator.
            return INSTANCE;
        }

What is meant by proper declaration here? Will the class even compile if the declaration is not proper? I am finding the sentence a little bit confusing.

Was it helpful?

Solution

From the javadoc of Serializable

Classes that need to designate a replacement when an instance of it is read from the stream should implement this special method with the exact signature.

ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;

So proper declaration means the method must have the same declaration as above.

This behavior exists because

Serializable serves as a marker to the JRE/JVM, which may take action(s) based on its presence.

But doesn't have any abstract methods declared of its own.

OTHER TIPS

Proper declaration means method must have this signature:

Object readResolve() throws ObjectStreamException;

During deserialization, after an object T was successfully deserialized, if object T contains a method readResolve() declared as above (via reflection, of course) it is automatically called.
Look this tutorial or official doc

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top