开发者

What does "proxy" object from invoke's method parameters list of java.lang.reflect.InvocationHandler represent?

I'm a little bit confused by this scenario:

I have a class that implements InvocationHandler interface mentioned in title, class that looks like :


class SimpleProxy implements InvocationHandler{
    
    private Object proxied;
    
    public SimpleProxy(Object proxied) {
        this.proxied = proxied;
    }
    
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        
        System.out.开发者_如何学编程println(proxy);
        return method.invoke(proxied, args);
        
    }
    
}

and lets say in my "main" method I have:


public static void main(String[] args) {
        
        consumer(new RealObject());
        
        MyInterface proxy = (MyInterface)Proxy.newProxyInstance(MainClass.class.getClassLoader(), new Class[]{MyInterface.class}, new SimpleProxy(new MyInterfaceImpl()));
        
        proxy.methodFromMyInterface();
        
    }

Now the problem is that the "invoke" throws an error like:

...

at rtti.SimpleProxy.invoke(MainClass.java:81)

at rtti.$Proxy0.toString(Unknown Source)

at java.lang.String.valueOf(String.java:2826)

at java.io.PrintStream.println(PrintStream.java:771)

at rtti.SimpleProxy.invoke(MainClass.java:81)

at rtti.$Proxy0.toString(Unknown Source)

at java.lang.String.valueOf(String.java:2826)

at java.io.PrintStream.println(PrintStream.java:771)

...

because of this line :

System.out.println(proxy);

If I comment this line everithing works fine.

Can anybody explain me what's the problem?

N.B. In the Java docs it says about invoke method from InvocationHandler:

Processes a method invocation on a proxy instance and returns the result. This method will be invoked on an invocation handler when a method is invoked on a proxy instance that it is associated with.

Parameters: proxy - the proxy instance that the method was invoked on

... so I can't understand why it is going wrong ...


System.out.println(proxy); will implicitly call toString() on the proxy, i.e. call a proxied method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜