How to use java proxy in scala

时间秒杀一切 提交于 2019-12-04 04:29:34

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

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