Created
November 23, 2011 14:34
-
-
Save viktorklang/1388812 to your computer and use it in GitHub Desktop.
Serialization of dynamic Proxies
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//An interface we'll secretly inject into the mix, in order to get Java Serialization to think we've implemented writeReplace | |
trait Replaceable { | |
@throws(classOf[java.io.ObjectStreamException]) | |
def writeReplace(): AnyRef | |
} | |
//An external representation of our Proxy | |
case class SerializedProxy(...) { //Whatever you need to store away in order to rematerialize | |
@throws(classOf[java.io.ObjectStreamException]) | |
def readResolve(): AnyRef = { | |
//Logic to re-appear as a proxy (on potentially a different machine etc) | |
} | |
} | |
//As always, you want to implement the behavior of your Proxy, and in here we trap the call to writeReplace | |
class YourInvocationHandler(...) extends InvocationHandler { | |
def invoke(proxy: AnyRef, method: Method, args: Array[AnyRef]): AnyRef = method.getName match { | |
case "writeReplace" if (args eq null) || args.length == 0 => SerializedProxy(...) //Profit! | |
//...toString, equals, hashCode, all other invocations | |
} | |
} | |
//When you create your Proxy, add Replaceable to the sequence of interfaces to proxy | |
val serializableProxy = Proxy.newProxyInstance(loader, interfaces :+ classOf[Replaceable], new YourInvocationHandler(...)).asInstanceOf[YourProxiedType] | |
//And now you can pass your serializableProxy to an ObjectOutputStream like a Boss! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment