调试java动态代理的代码时,发现代理对象中的invoke方法中的语句重复执行。运行时正常。
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("明天");
}
}
你咋调试的 我就输出一次啊