1

I have checked this stackoverflow post. But still I did not understand.

In JDK proxy, the Proxy.newInstance(arg1,arg2,arg3) creates the new proxy instance. when we call a method on this proxy instance it calls its associated invocation handler. Invocation handler's invoke method delegates the call to the actual method.

The invoke method has 3 arguments. The first one is mentioned as proxy instance on which the call is made. My doubt is how the proxy instance is passed to invocation handler invoke method?

To understand my doubt more clearly, Please see my code below.

Interface

package proxyclasses;

public interface Animal {
    public abstract void eat(String food);
}

Concrete Class

package proxyclasses;

public class Cow implements Animal {

    public void eat(String food) {
        System.out.println("Cow eats "+food);
    }

}

Proxy Class

package proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MyInvocationHandler implements InvocationHandler {

    private Object target;

    public MyInvocationHandler(Object target) {
        this.target = target;
    }
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        System.out.println("Proxy "+proxy.getClass().getName());
        Object result = method.invoke(target, args);
        return result;
    }

}

Main Class

import java.lang.reflect.Proxy;

import proxy.MyInvocationHandler;
import proxyclasses.Animal;
import proxyclasses.Cow;


public class ProxyExample {
    public static void main(String args[]){
        Cow cow = new Cow();
        Animal proxInstance = (Animal)Proxy.newProxyInstance(Cow.class.getClassLoader(),Cow.class.getInterfaces(),new MyInvocationHandler(cow));
        proxInstance.eat("Grass");
    }
}

Here my doubt is how the 'proxInstance ' in main class is passed to myInvocationHandlers invoke method?

Community
  • 1
  • 1
Sivaranjani D
  • 512
  • 4
  • 16
  • I assume since understand proxies, you understand how a reference is passed to a method call, so I don't understand what it is you are asking. – Peter Lawrey Apr 12 '16 at 09:40

1 Answers1

0

Here my doubt is how the 'proxInstance ' in main class is passed to myInvocationHandlers invoke method?

You appear to have answered your own question.

when we call a method on this proxy instance it calls its associated invocation handler

So you have something like

Method method = ...
Object[] args = ...
handler.invoke(this, method, args);

Where this is the Proxy object which wraps the handler, the proxy which you called.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130