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

来源:互联网 发布:淘宝超过时间不能评价 编辑:程序博客网 时间:2024/05/20 05:08

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


0 0
原创粉丝点击