2014-02-05 55 views
7

我有一個接口作爲Iface,它有兩種用java編寫的方法。該接口是Zzz類的內部接口。 我已經在scala中編寫了調用處理程序。然後我嘗試在下面的scala中創建一個新的代理實例。如何在scala中使用java代理

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] 

但這裏的編譯器說,

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

我怎樣才能做到這一點具有代理,在很短的方式。

回答

8

這裏是你的代碼的固定版本。它也編譯,甚至做一些事情!

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() 
    } 

} 
+0

關於你改變了什麼以及爲什麼會有啓發性的小討論。 –