views:

1376

answers:

3

Alas, Google has failed me...

What is the Serialization Proxy Pattern and where can I learn more about implementing and using it?

A: 

The first link in google search looks helpful: Effective Java on serialization proxy

Igor Brejc
I did read that one but it seems the excerpt is partial so I'm hoping for more.
urig
Well from what I've googled around, looks like that book is a reference for what you're looking for. Other articles mention the same book.
Igor Brejc
+1  A: 

There is a sample implementation in this answer.

McDowell
+2  A: 

There's a nice description in the last section of Josh Bloch's Effective Java, Second Edition.

Suppose you have a class A that you would like to make serializable. You first declare it to implement Serializable. Then you use the serialization method writeReplace() to return a so-called "serialization proxy" that will be serialized in place of the instance of A. The writeReplace() method does not need to be public. The default serialization on A never gets invoked, so all of the API properites of A may be maintained.

Typically, the proxy is implemented as a private static nested class that itself must implement Serializable (or Externalizable for complete control of the read/write process). Because the proxy is private, its implementation details, such as having a no-arg constructor and being mutable, will be hidden.

The proxy stores enough of the state of the original object to write so that it can reconstitute the object on deserialization. On deserialization, the proxy uses the method readResolve() to return an instance of A. For singletons, this can be the singleton instance itself.

I wrote up a detailed blog entry with examples, Serializing Immutables and Singletons with a Serialization Proxy.

Bob Carpenter
I was wondering if the serialization proxy could be Externalizable. The book only mentions Serializable. Thanks!
Craig P. Motlin