Java dynamic proxy, number of invoke method calls

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("");
    }
}


how do you debug it? I'll output it once


whether it outputs two invoke contents. Because hello is a proxy object, any method call to hello will trigger the call to the invoke function again.


this is because in debug mode, if the editor sets this mode to display object information, the toString () method will be called by default and will be called again when the mouse moves over the object. So it will be output all the time. (it can be verified by overriding the toString () method of the proxied object) ![![] [1]

Menu