Geek
Geek

Reputation: 27219

How will the readResolve() method of the proxy class get called in the Serialization Proxy pattern?

I am studying up on Serialization Proxy pattern. It basically says to have a a proxy class that should be declared as a static nested class of the enclosing class that we want to serialize. So the basic idea is that the proxy shields the enclosing serializable class from perils of Serialization.

However the implementation isn't actually clear to me . Why do we call the writeReplace() on the outer class and the readResolve() on the proxy class? Since the proxy class is like a static member of the outer class how will it even get serialized? If it does not get serialized then how will the readResolve() be called on the proxy during deserialization?

I am sure I am missing something basic here. Can someone shed some light?

Upvotes: 0

Views: 852

Answers (1)

axtavt
axtavt

Reputation: 242786

Check the documentation of Serializable.

writeReplace() and readResolve() are special methods called by serialization engine.

writeReplace() replaces object being serialized with the proxy, and readResolve() replaces deserialized proxy with the actual object.

Serialization proxy class doesn't have to be a static nested class of the class you want to serialize. It's just a convention for better organization of code.

Upvotes: 2

Related Questions