A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© chenzhiyuan   /  2014-6-3 13:24  /  1847 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

求一个ArrayList的代理?

2 个回复

倒序浏览
public class Test2 {
// ArraiList代理类的测试
public static void main(String[] ages) {
  MyArrayListInterface myArrayList =ArrayListProxy.getArrayListProxy();
  myArrayList.add("AAAAA");
  System.out.println(myArrayList.get(0));
}
// 定义一个ArrayList的代理类
static class ArrayListProxy {
  // 定义一个返回ArrayListProxy对象的方法
  public static MyArrayListInterface getArrayListProxy() {
   MyArrayListInterface myArrayListProxy = (MyArrayListInterface) Proxy
     .newProxyInstance(MyArrayListInterface.class
       .getClassLoader(),
       new Class[] { MyArrayListInterface.class },
       new InvocationHandler() {
        // 定义一个MyArrayList对象
        private List myArrayList = new MyArrayList();
        public Object invoke(Object proxy,
          Method method, Object[] args)
          throws Throwable {
         // 定义记住此时时间的变量
         long start = System.currentTimeMillis();
         // 执行al的对应方法
         Object objReturn = method.invoke(
           myArrayList, args);
         // 输出被调用方法执行的所需时间
         System.out.println(method.getName()+"方法运行时间:"+(System
           .currentTimeMillis()
           - start)+"毫秒");
         return objReturn;// 返回被调用方法执行结果
        }
       });
   return myArrayListProxy;
  }
}
}
// 定义一个实现MyArrayListInterface的类MyArrayList
class MyArrayList extends ArrayList implements MyArrayListInterface {
}
// 定义一个接口,同时继承ArrayList类实现的全部接口
interface MyArrayListInterface<E> extends Serializable, Cloneable, Iterable<E>,
  Collection<E>, List<E>, RandomAccess {
}

评分

参与人数 1技术分 +1 收起 理由
SyouRai_Tsk + 1

查看全部评分

回复 使用道具 举报
public static MyArrayListInterface getArrayListProxy() {    MyArrayListInterface myArrayListProxy = (MyArrayListInterface) Proxy      .newProxyInstance(MyArrayListInterface.class        .getClassLoader(),        new Class[] { MyArrayListInterface.class }
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马