如何在Scala中使用Java代理 [英] How to use java proxy in scala
本文介绍了如何在Scala中使用Java代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Iface接口,它有两个用Java编写的方法.该接口是Zzz类的内部接口. 我已经在Scala中编写了调用处理程序.然后,我尝试在如下所示的scala中创建一个新的代理实例.
I have an interface as Iface that has two methods written in java. That interface is an inner interface of Zzz class. I have written the invocation handler in scala. Then I tried to create a new proxy instance in scala like 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]
但是在这里编译器说
$Proxy0 cannot be cast to xxx.yyy.Zzz$Iface
如何在短时间内通过代理实现此功能.
How can I do this with proxy, in a short way.
推荐答案
这是您代码的固定版本.它还可以编译甚至执行某些操作!
Here is the fixed version of your code. Also it 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()
}
}
这篇关于如何在Scala中使用Java代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文