package cn.itcast.day8;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
public class ProxyTest {
/**
* @param args
* @throws NoSuchMethodException
* @throws SecurityException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws IllegalArgumentException
*/
public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
Class clazzProxy1 = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
Collection proxy3 = (Collection) Proxy.newProxyInstance(
Collection.class.getClassLoader(),
new Class[] {Collection.class},
new InvocationHandler(){
ArrayList target = new ArrayList();
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
long startTime = System.currentTimeMillis();
Object returnVal = method.invoke(target, args);
long endTime = System.currentTimeMillis();
System.out.println(method.getName() + ":runing time of:" + (endTime - startTime));
return returnVal;
}
}
);
proxy3.add("baba");
proxy3.add("mama");
proxy3.add("hehe");
System.out.println(proxy3);
System.out.println(proxy3.size());
System.out.println(proxy3.getClass());
}
}
结果:
add:runing time of:0
add:runing time of:0
add:runing time of:0
toString:runing time of:0
[baba, mama, hehe]
size:runing time of:0
3
class $Proxy0
提问:
jdk1.6中说道:
如果代理接口包含某一方法,它的名称和参数签名与 java.lang.Object 的 hashCode、equals 或 toString 方法相同,那么在代理实例上调用这样的方法时,传递到调用处理程序的 Method 对象将使 java.lang.Object 成为其声明类。换句话说,java.lang.Object 公共的非最终方法理论上在所有代理接口之前,以便确定哪一个 Method 对象传递到调用处理程序。
但是:这里的size( )方法用到了还是用到了Invocation对象中的invoke( )方法!!
哪位大侠能帮小弟解释清楚么?
|