黑马程序员技术交流社区

标题: 动态代理 [打印本页]

作者: 奋发吧小白    时间: 2014-9-16 12:12
标题: 动态代理
需求:为Arraylist集合创建一个动态代理
  1. package interview;

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

  7. public class ProxyDemo01 {

  8.         /**
  9.          * @param args
  10.          */
  11.         public static void main(String[] args) {
  12.                 // TODO Auto-generated method stub
  13.                 Class clazzProy = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
  14.                 Collection proxy = (Collection)Proxy.newProxyInstance(
  15.                                 Collection.class.getClassLoader(),
  16.                                 new Class[] {Collection.class},
  17.                                 new InvocationHandler()
  18.                                 {
  19.                                         ArrayList target = new ArrayList();
  20.                                         public Object invoke(Object proxy, Method method, Object[] args)
  21.                                                         throws Throwable {
  22.                                                 Object retVal = method.invoke(target, args);
  23.                                                 return retVal;
  24.                                         }
  25.                                        
  26.                                 }
  27.                                 );
  28.                 proxy.add("nihi");
  29.                 proxy.add("sajd");
  30.                 proxy.add("sad");
  31.                 System.out.println(proxy);
  32.         }

  33. }
复制代码




作者: Nullifier    时间: 2014-9-16 13:02
刚看完动态代理,在复习一遍




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