is it possible to have a method that takes an arbitrary instance and returns a java.reflection.Proxy or similar that has the same type as the original argument?
I guess it should look something like this:
def createProxy[S](model: S)(implicit manifest: Manifest[S]): S = {...}
or this
def createProxy[S, T<:S](model: S)(implicit manifest: Manifest[S]): T = {...}
where T is the subtype of S which results from a combination of all the implemented interfaces, since it doesn't seem like I can Proxy an actual class, but only interfaces.
I think the following should do the trick. Note that it can't return an S since it's likely S is not an interface.
import java.lang.reflect._
def createProxy[S](model: S)(implicit manifest: Manifest[S]) = {
val clazz = manifest.erasure
Proxy.newProxyInstance(clazz.getClassLoader, clazz.getInterfaces, new InvocationHandler() {
def invoke(proxy:Object, method:Method, args:scala.Array[Object]) = {
method.invoke(model, args:_*)
}
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With