黑马程序员技术交流社区

标题: 代理类的问题 [打印本页]

作者: NNERO    时间: 2014-4-22 21:43
标题: 代理类的问题
  1. import java.lang.reflect.*;
  2. import java.util.*;

  3. public class ProxyDemo {

  4.         public static void main(String[] args) {
  5.                
  6.                 Collection<Integer> proxy =  getProxy(Integer.class);
  7.                 Collection<String> proxy2 =  getProxy(String.class);
  8.                 proxy.add(11);
  9.                 proxy.add(22);
  10.                 proxy2.add("hahahahahahahahahaha");
  11.        
  12.                 System.out.println(proxy);
  13.                 System.out.println(proxy2);
  14.                
  15.         }
  16.         @SuppressWarnings("unchecked")
  17.         public static <E> ArrayList<E> getProxy(Class<E> eType){
  18.                
  19.                 ArrayList<E> al = (ArrayList<E>) Proxy.newProxyInstance(
  20.                                 ArrayList.class.getClassLoader(),  //这里是什么意思,用类加载器加载代理类吗?
  21.                                 ArrayList.class.getInterfaces(), //这里也不懂
  22.                                 new InvocationHandler() {
  23.                                         ArrayList<E> list = new ArrayList<E>();
  24.                                         @Override
  25.                                         public Object invoke(Object proxy, Method method, Object[] args)
  26.                                                         throws Throwable {
  27.                                                 Object reval = method.invoke(list, args);
  28.                                                 return reval;
  29.                                         }
  30.                                 });
  31.                 return (ArrayList<E>)al;
  32.         }
  33. }
复制代码
注释里的2个问题。
还有这个程序运行出错啊,说什么类型转换失败。这个怎么办,求解答!

作者: osully    时间: 2014-4-22 22:00
老实说  你这个代理 写的真是一塌糊涂

再看一遍张老师的视频吧
作者: 云浮    时间: 2014-4-22 22:42
不过我还是建议他看一下api




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2