2014-02-05 2 views
7

Java에서 작성된 두 가지 메소드가있는 Iface 인터페이스가 있습니다. 이 인터페이스는 Zzz 클래스의 내부 인터페이스입니다. 나는 scala에 호출 핸들러를 작성했다. 그런 다음 아래와 같이 스케이라에 새 프록시 인스턴스를 만들려고했습니다. scala에서 java 프록시를 사용하는 방법

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 

가 어떻게 짧은 방법으로, 프록시를 사용하여이 작업을 수행 할 수 있다고 말한다.

답변

8

다음은 고정 된 버전의 코드입니다. 또한 컴파일되고 심지어 무언가를합니다!

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

} 
+0

당신이 무엇을 바꿨으며 왜 깨달았는지에 대한 약간의 토론. –