黑马程序员技术交流社区

标题: Proxy动态生成的类,为什么只能是接口 [打印本页]

作者: 马上都有    时间: 2014-5-20 17:10
标题: Proxy动态生成的类,为什么只能是接口
  1. /**

  2.          * 练习使用代理,添加功能

  3.          * @param args

  4.          */

  5.         public static void main(String[] args) {

  6.                 // TODO Auto-generated method stub

  7.                 HashSet has =(HashSet)Proxy.newProxyInstance(

  8.                                 //这一步是告诉proxy用哪个类加载器加载这个类

  9.                                 HashSet.class.getClassLoader(),
  10.                                 //这一步是为了告诉动态生成类的proxy,要生成什么样的类

  11.                                 new Class[]{HashSet.class},
  12.                                 //这个参数是代理的关键参数,这个参数的作用是对要代理的方法进行操作

  13.                                 new InvocationHandler() {

  14.                                         HashSet set = new HashSet();

  15.                                         @Override

  16.                                         public Object invoke(Object proxy, Method method, Object[] args)

  17.                                                         throws Throwable {

  18.                                                 // TODO Auto-generated method stub

  19.                                         Object retVal = method.invoke(set, args);

  20.                                                 return retVal;

  21.                                         }

  22.                                 }

  23.                                 );

  24.                 //has.hashCode();

  25.                 has.add("hllo");

  26.                
  27.         }
复制代码


作者: 艮昕辶    时间: 2014-5-21 17:50
要代理的目标类不一定是接口吧
newProxyInstance(Target.class.getClassLoader(),Target.class.getInterfaces(),handler);
作者: 不似侽紸角.    时间: 2014-5-21 20:50
这么说吧,代理要为目标增加功能,那么增加功能的方法通过代理传递给目标,所以目标有的方法代理也必须有,
所以要实现相同的接口啦




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