How to use Java proxies in scala

I have an interface like Iface, which has two methods written in java. This interface is the internal interface of the Zzz class. I wrote a call handler in scala. Then I tried to create a new proxy instance in scala, as shown below.

val handler = new ProxyInvocationHandler // this handler implements //InvocationHandler interface val impl = Proxy.newProxyInstance( Class.forName(classOf[Iface].getName).getClassLoader(), Class.forName(classOf[Iface].getName).getClasses, handler ).asInstanceOf[Iface] 

But here the compiler says that

 $Proxy0 cannot be cast to xxx.yyy.Zzz$Iface 

How can I do this using a proxy server in a short time.

+7
java scala inner-classes proxy-classes
source share
1 answer

Here is a fixed version of your code. He also compiles and even does something!

 import java.lang.reflect.{Method, InvocationHandler, Proxy} object ProxyTesting { class ProxyInvocationHandler extends InvocationHandler { def invoke(proxy: scala.AnyRef, method: Method, args: Array[AnyRef]): AnyRef = { println("Hello Stackoverflow when invoking method with name \"%s\"".format(method.getName)) proxy } } trait Iface { def doNothing() } def main(args: Array[String]) { val handler = new ProxyInvocationHandler val impl = Proxy.newProxyInstance( classOf[Iface].getClassLoader, Array(classOf[Iface]), handler ).asInstanceOf[Iface] impl.doNothing() } } 
+8
source share

All Articles