黑马程序员技术交流社区

标题: 关于张孝祥老师的基础加强中动态代理技术的问题 [打印本页]

作者: taomingking    时间: 2013-7-26 16:06
标题: 关于张孝祥老师的基础加强中动态代理技术的问题
本帖最后由 杨兴庭 于 2013-7-29 11:03 编辑

我用做好的创建代理方法,想要创建一个ArrayList的代理,为什么我传进一个ArrayList对象,得到的只能是List或者Collection对象?如果强转成ArrayList会报错,这是什么原因呢?
下面是代码:
  1. package com.study.day3;
  2. import java.lang.reflect.Constructor;
  3. import java.lang.reflect.InvocationHandler;
  4. import java.lang.reflect.InvocationTargetException;
  5. import java.lang.reflect.Method;
  6. import java.lang.reflect.Proxy;
  7. import java.util.ArrayList;
  8. import java.util.Collection;

  9. public class TestTest {
  10.         public static void main(String[] args) throws Exception {
  11.                
  12.                 ArrayList target = new ArrayList();
  13.                 Advise advise = new MyAdvise();
  14.                 Collection proxy4 = (Collection) getProxy(target,advise);//问题在这里,只能用强转成Collection和List,不能专程ArrayList

  15.                 System.out.println(proxy4.toString());//注意:从Object继承来的方法,只有toString,hashCode,equals,
  16.                 System.out.println(proxy4.getClass());//调用时委托给InvocationHandler,其他的方法Proxy自己都有实现.

  17.         }
  18.         
  19.         private static Object getProxy(final Object target,final Advise advise) {
  20.                 Object proxy3 = Proxy.newProxyInstance(
  21.                                 target.getClass().getClassLoader(),
  22.                                 target.getClass().getInterfaces(),
  23.                                 new InvocationHandler(){
  24.                                         @Override
  25.                                         public Object invoke(Object proxy, Method method, Object[] args)
  26.                                                         throws Throwable {
  27.                                                 
  28.                                                 advise.before(method);
  29.                                                 Object reValue = method.invoke(target, args);
  30.                                                 advise.after(method);
  31.                                                 return reValue;
  32.                                         }
  33.                                 }
  34.                                 );
  35.                 return proxy3;
  36.         }
  37. }
复制代码

作者: 万琪    时间: 2013-7-26 19:25
,,自然是这样的,,,你没看代理是面向接口的吗
作者: taomingking    时间: 2013-7-27 21:29
万琪 发表于 2013-7-26 19:25
,,自然是这样的,,,你没看代理是面向接口的吗

就是说我创建一个类的代理,这个代理不能实现这个类的全部功能,只能实现这个类的接口的全部功能的意思吗?




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