Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Proxy without explicitely specifying the type in scala

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.

like image 404
Jens Schauder Avatar asked Oct 10 '10 15:10

Jens Schauder


1 Answers

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:_*)
    }
  })
}
like image 144
Hiram Chirino Avatar answered Oct 02 '22 15:10

Hiram Chirino