package shoujiTest;
import java.awt.List;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
import org.omg.CORBA.portable.InvokeHandler;
/**
* 写一个ArrayList类的代理,实现和ArrayList中完全相同的功能,并可以计算每个方法运行的时间。
* */
public class Test2 {
/*public static <T> void main(String[] args) throws Exception {
final ArrayList<T> target=new ArrayList<T>();
Collection proxy=(Collection)Proxy.newProxyInstance(Collection.class.getClassLoader(),
new Class[]{Collection.class},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Long beginTime=System.currentTimeMillis();
Object retVal=method.invoke(target, args);
Long endTime=System.currentTimeMillis();
System.out.println(method.getName()+"running time of"+(endTime-beginTime));
return retVal;
}
});
proxy.add("zhangsan");
proxy.add("lisi");
proxy.add("wangwu");
System.out.println(proxy.size());
}*/
public static <T> void main(String[] args) throws Exception {
final ArrayList<T> target=new ArrayList<T>();
Collection proxy =(Collection) getProxy(target,new MyAdvice());
proxy.add("zhangsan");
proxy.add("lisi");
proxy.add("wangwu");
System.out.println(proxy.size());
}
private static Object getProxy(final Object target,final Advice advice ) {
Object proxy=Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
//Long beginTime=System.currentTimeMillis();
advice.beforTime(method);
Object retVal=method.invoke(target, args);
advice.afterTime(method);
//Long endTime=System.currentTimeMillis();
//System.out.println(method.getName()+"running time of"+(endTime-beginTime));
return retVal;
}
});
return proxy;
}
}
interface Advice{
public abstract void beforTime(Method method);
public abstract void afterTime(Method method);
}
class MyAdvice implements Advice{
Long beginTime;
public void beforTime(Method meethod){
System.out.println("到黑马学习啦");
beginTime=System.currentTimeMillis();
}
public void afterTime(Method method){
System.out.println("从黑马毕业要参加工作啦");
Long endTime=System.currentTimeMillis();
System.out.println(method.getName()+" running time of"+(endTime-beginTime));
}
}
:call: |
|