Search code examples
javadynamic-proxy

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 ...


Solution

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