How to use java proxy in scala

我与影子孤独终老i 提交于 2019-12-09 16:44:55

问题


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]

But here the compiler says that

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

How can I do this with proxy, in a short way.


回答1:


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

}


来源:https://stackoverflow.com/questions/21576065/how-to-use-java-proxy-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!