package com.itheima.day3;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
public class PorxyTest {
public static void main(String[] args) throws Exception
{
Class clazzProxy = Proxy.getProxyClass(Collection.class
.getClassLoader(), Collection.class);
System.out.println(clazzProxy.getName());
Constructor con=clazzProxy.getConstructor(InvocationHandler.class);
class MyInvocationHandler1 implements InvocationHandler
{
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
return null;
}
}
Collection proxy1=(Collection)con.newInstance(new MyInvocationHandler1());
System.out.println(proxy1);
proxy1.clear();
Collection proxy2=(Collection)con.newInstance(new InvocationHandler(){
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
return null;
}
});
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(startTime+"-->"+endTime);
System.out.println(method.getName()+"..."+(endTime-startTime));
return returnVal;
}
}
);
proxy1,proxy2,proxy3即为创建的代理类,本质一样,只是表现方式有所不同
|