0

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

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yes. You have lit me. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.