黑马程序员技术交流社区

标题: 动态代理的三种实现方式 [打印本页]

作者: 57xiaoyu    时间: 2015-4-4 13:17
标题: 动态代理的三种实现方式

第一种:

Constructor constructor = clazzProxy.getConstructor(InvocationHandler.class);
  Collection proxy = (Collection) constructor.newInstance(new MyInvocationhandler());

//MyInvocationhandler为实现InvocationHandler接口的类作为参数传入
  System.out.println(proxy);

第二种:

Collection proxy2 = (Collection) constructor .newInstance(new InvocationHandler() {

     public Object invoke(Object proxy, Method method,Object[] args) throws Throwable {
                    return null;
     }

    });// 这种方式 同第一种类似,只不过是将参数换成实现InvocationHandler接口的子类,而且是内部类

第三种:

final ArrayList target=new ArrayList();

Collection proxy3 = (Collection) Proxy.newProxyInstance(

            Collection.class.getClassLoader(),
            new Class[] { Collection.class },

    new InvocationHandler() {
     public Object invoke(Object proxy, Method method,
       Object[] args) throws Throwable {
       retObj = method.invoke(target, args);
       return retObj;     
           }
    });
proxy3.add("abcd");
  System.out.println(proxy3);
//这种方法即使用Proxy类中一个静态方法newProxyInstance(ClassLoader loader.class<?>[] interfaces,InvocationHandler h)创建。
注:当执行proxy3.add("abcd");时,代理对象proxy3对应invoke方法中proxy参数;.add方法对应invoke方法中method参数;而"abcd"参数则对应invoke方法中args参数,InvocationHandler接口的执行原理就是如此。
如果把目标对象和在代理类中添加的系统功能封装成对象传入代理类,即面向方面编程:把切面的代码以对象的方式进行封装,传给代理类。
例如:
public static Object getProxy(final Object target, final Advice advice) {
  Object proxy3 = Proxy.newProxyInstance(
    target.getClass() .getClassLoader(),
    target.getClass().getInterfaces(),
    new InvocationHandler() {
     @Override
     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            advice.beforeExecute(method);
            Object retVal = method.invoke(target, args);
             advice.afterExecute(method);
             return retVal;
           }
   });
  return proxy3;
}
//advice是一个接口,它有两个方法,在它的实现类中实现在代理类中其它系统功能,即把系统功能封装成advice对象,以参数形式传入获得代理类的方法中。






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