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?