黑马程序员技术交流社区

标题: 动态代理程序中有点小问题(问题在程序中注释) [打印本页]

作者: HM王琦    时间: 2013-3-16 19:41
标题: 动态代理程序中有点小问题(问题在程序中注释)
  1. package cn.whap.wq3;

  2. import java.lang.reflect.Constructor;
  3. import java.lang.reflect.InvocationHandler;
  4. import java.lang.reflect.Method;
  5. import java.lang.reflect.Proxy;
  6. import java.util.ArrayList;
  7. import java.util.Collection;
  8. import java.util.Iterator;

  9. public class ProxyTest {

  10.         /**
  11.          * @param args
  12.          */
  13.         public static void main(String[] args) throws Exception{
  14.                 // TODO Auto-generated method stub
  15.                 Class clazzProxy1=Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
  16.                
  17.                 Collection Proxy2=(Collection) Proxy.newProxyInstance(Collection.class.getClassLoader(),
  18.                                 new Class[] {Collection.class},
  19.                                 new InvocationHandler(){
  20.                         ArrayList target=new ArrayList();
  21.                         @Override
  22.                         public Object invoke(Object proxy, Method method, Object[] args)
  23.                                         throws Throwable {
  24.                                
  25.                                 Object value=method.invoke(target, args);//此处method.invoke()方法,
  26.                                                                                                                 //是那里来的,在程序里没有定义method对象。
  27.                                 return value;
  28.                         }
  29.                        
  30.                 });
  31.                 Proxy2.add("zxx");
  32.                 Proxy2.add("bxd");
  33.                 Proxy2.add("llx");
  34.                 Iterator it=Proxy2.iterator();
  35.                 while(it.hasNext()){
  36.                         System.out.println(it.next());
  37.                 }
  38.                 System.out.println(Proxy2.size());
  39.                
  40.                
  41.                          
  42.         }
  43.                
  44.        
  45. }

复制代码

作者: 黑马李超    时间: 2013-3-16 20:08
     public Object invoke(Object proxy, Method method, Object[] args)//这里传入了Method对象
                                        throws Throwable {
                                
                                Object value=method.invoke(target, args);//此处method.invoke()方法,
                                                                                                                //是那里来的,在程序里没有定义method对象。
                                return value;
                        }
作者: HM张超    时间: 2013-3-16 23:21
楼上正解




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