bul*_*ula 7 java scala proxy-classes inner-classes
我有一个Iface接口,它有两个用java编写的方法.该接口是Zzz类的内部接口.我在scala中编写了调用处理程序.然后我尝试在scala中创建一个新的代理实例,如下所示.
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]
Run Code Online (Sandbox Code Playgroud)
但编译器在这里说
$Proxy0 cannot be cast to xxx.yyy.Zzz$Iface
Run Code Online (Sandbox Code Playgroud)
我怎样才能以简短的方式使用代理.
这是您的代码的固定版本.它也编译甚至做某事!
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()
}
}
Run Code Online (Sandbox Code Playgroud)