鍍金池/ 問答/Java  網(wǎng)絡安全/ java動態(tài)代理,invoke方法調(diào)用的次數(shù)

java動態(tài)代理,invoke方法調(diào)用的次數(shù)

調(diào)試java動態(tài)代理的代碼時,發(fā)現(xiàn)代理對象中的invoke方法中的語句重復執(zhí)行。運行時正常。

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

圖片描述

回答
編輯回答
糖豆豆

你咋調(diào)試的 我就輸出一次啊

2018年9月13日 06:38
編輯回答
愛是癌

是不是輸出了兩個invoke的內(nèi)容·。由于hello是一個代理對象, 所以hello的任何方法調(diào)用,都會再次觸發(fā)invoke函數(shù)的調(diào)用。

2017年4月15日 02:49