when debugging the code of the java dynamic proxy, you found that the statement in the invoke method in the proxy object was executed repeatedly. It runs normally.
public class DynamicProxyHello implements InvocationHandler{
private Object proxy;
private Object target;
public Object bind(Object target,Object proxy){
this.target=target;
this.proxy=proxy;
return Proxy.newProxyInstance(this.target.getClass().getClassLoader(),
this.target.getClass().getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result=null;
Class clazz=this.proxy.getClass();
Method start=clazz.getDeclaredMethod("start",new Class[]{Method.class});
start.invoke(this.proxy,start);
method.invoke(this.target,args);
Method end=clazz.getDeclaredMethod("end",new Class[]{Method.class});
end.invoke(this.proxy,end);
return result;
}
}
public class DLogger implements ILogger{
@Override
public void start(Method method) {
System.out.println(new Date()+method.getName()+" say hello start...");
}
@Override
public void end(Method method) {
System.out.println(new Date()+method.getName()+" say hello end...");
}
}
public class Hello implements IHello{
@Override
public void sayHello(String str) {
System.out.println("hello "+str);
}
}
public interface ILogger {
void start(Method method);
void end(Method method);
}
public class Test {
public static void main(String[] args) {
IHello hello=(IHello) new DynamicProxyHello().bind(new Hello(),new DLogger());
hello.sayHello("");
}
}