给集合ArrayList集合创建一个动态代理并向里面添加元素
package interview;
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 ProxyDemo01 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Class clazzProy = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
Collection proxy = (Collection)Proxy.newProxyInstance(
Collection.class.getClassLoader(),
new Class[] {Collection.class},
new InvocationHandler()
{
ArrayList target = new ArrayList();
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object retVal = method.invoke(target, args);
return retVal;
}
}
);
proxy.add("nihi");
proxy.add("sajd");
proxy.add("sad");
System.out.println(proxy);
}
}
------- android培训、 java培训、期待与您交流! ----------