views:

1606

answers:

2

The book Effective Java and other sources provide a pretty good explanation on how and when to use the readObject() method when working with serializable Java classes. The readResolve() method, on the other hand, remains a bit of a mystery. Basically all documents I found either mention only one of the two or mention both only individually.

Questions that remain unanswered are:

  • What is the difference between the two methods?
  • When should which method be implemented?
  • How should readResolve() be used, especially in terms of returning what?

I hope you can shed some light on this matter.

+3  A: 

readResolve is used for replacing the object read from the stream. The only use I've ever seen for this is enforcing singletons; when an object is read, replace it with the singleton instance. This ensures that nobody can create another instance by serializing and deserializing the singleton.

Michael Myers
There is a number of way for malicious code (or even data) to get around that.
Tom Hawtin - tackline
Ooh, tell me more! >:D
Michael Myers
Yes, please explain. Flyweight patterns rely on this working, so how can it break?
Steve Armstrong
Josh Bloch talks about the conditions under which this breaks in effective Java 2nd ed. Item 77. He mentions about this in this talk he gave in Google IO couple of years back (some times towards the end of the talk): http://www.youtube.com/watch?v=pi_I7oD_uGI
calvinkrishy
+1  A: 

readResolve is called after readObject has returned (conversely writeResolve is called before writeObject and probably on a different object). The object the method returns replaces this object returned to the user of ObjectInputStream.readObject and any further back references to the object in the stream. It is mostly used for serial proxies (see Effective Java, 2nd Ed, IIRC).

Tom Hawtin - tackline