I'm learning about java dynamic proxy, and here's my code:
//interface Move.java
public interface Move {
public void testMove();
}
then the implementation class
public class Tank implements Move{
public void testMove() {
System.out.println("test in Tank");
}
}
followed by
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MoveHandler implements InvocationHandler{
private Object target;
public MoveHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("in MoveHandler");
Object ret;
try {
ret = method.invoke(target, args);
}catch (Exception e) {
e.printStackTrace();
throw e;
}
System.out.println("after MoveHandler");
return ret;
}
}
test class
public class Main {
public static void main(String[] args) {
Move test = new Tank();
MoveHandler proxy = new MoveHandler(test);
Move real = (Move) Proxy.newProxyInstance(test.getClass().getClassLoader(), test.getClass().getInterfaces(), proxy);
real.testMove();
}
}
I can get the right result when I run the Main class. If I change method.invoke(target, args) into method.invoke(proxy, args), there will be thousand lines of exception and errors. What's the usage of the argument proxy in invoke(Object proxy, Method method, Object[] args) and how can I use it correctly?