我有一个 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]
但这里编译器说
$Proxy0 cannot be cast to xxx.yyy.Zzz$Iface
我怎样才能用代理来做到这一点,以简短的方式。
这是代码的固定版本。它还可以编译,甚至可以做一些事情!
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()
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)