interface Advice {
void beforeMethod(Method method);
void afterMethod(Method method);
}
class MyAdvice implements Advice {
long beginTime=0;
public void afterMethod(Method method) {
long endTime=System.currentTimeMillis();
System.out.println(method.getName()+":"+"run"+":"+(endTime-beginTime));
}
public void beforeMethod(Method method) {
long beginTime=System.currentTimeMillis();
}
}
//代理调试类主函数中有
final ArrayList target=new ArrayList ();
Collection proxy4 = (Collection)getProxy(target,new MyAdvice());
proxy4.add("x");
proxy4.add("y");
proxy4.add("z");
System.out.println(proxy4.size());
System.out.println(proxy4.getClass().getName());
//为什么调用目标方法?而代理类也有值 System.out.println(proxy4);//[x, y, z]
//代理测试类的一个方法次,此方法获得目标类的代理的方法 private static Object getProxy(final Object target,final Advice advice) {
Object proxy4=(Object)Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler(){
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
advice.beforeMethod(method);
Object retVal=method.invoke(target, args);
advice.afterMethod(method);
return retVal;
}
});
return proxy4;
}
}
//为什么调用目标方法?而代理类也有值 System.out.println(proxy4);//[x, y, z]
客服端调用代理各个方法时,把请求转发给InvocationHandler对象,分发给目标的各个方法,
add方法运行原理是 Boolean add(Object obj){ handler.invoke(this, this.getClass().getMethod("add"), obj); }
但是我们查看invoke方法,发现并没有对代理类进行操作,那么打印System.out.println(proxy4)时候;
代理对象何时装了三个元素x,y,z? |