黑马程序员 【】java学习之路-------------简写动态代理

时间:2020-12-14 00:45:38

给集合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 stubClass 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培训、期待与您交流! ----------