动态代理对象的创建---------------理解了这段代码,你就懂了动态代理了

JDK中:

java.lang.reflect
类 Proxy

java.lang.Object
  继承者 java.lang.reflect.Proxy

创建某一接口 Foo 的代理:

     InvocationHandler handler = new MyInvocationHandler(...);
     Class proxyClass = Proxy.getProxyClass(
         Foo.class.getClassLoader(), new Class[] { Foo.class });
     Foo f = (Foo) proxyClass.
         getConstructor(new Class[] { InvocationHandler.class }).
         newInstance(new Object[] { handler });
 

或使用以下更简单的方法:

     Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
                                          new Class[] { Foo.class },
                                          handler);

 

//实例测试如下

///上面部分的复杂方式

Class clazzProxy1 = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
 Constructor constructor = clazzProxy1.getConstructor(InvocationHandler.class);
 Collection proxy1 = (Collection)constructor.newInstance(new InvocationHandler(){
   public Object invoke(Object proxy, Method method, Object[] args)
     throws Throwable {
     advice.beforeMethod(method);
      Object retVal = method.invoke(target, args);
      advice.afterMethod(method);
     return retVal; 
   }
   
  });

、更简洁方式

 

private static Object getProxy(final Object target,final Advice advice) {//传递目标对象和切面类
  Object proxy3 = Proxy.newProxyInstance(//用newProxyInstance方式得到目标类的代理实例对象

    target.getClass().getClassLoader(),//参数一:目标类的类加载器
    /*new Class[]{Collection.class},*/


    target.getClass().getInterfaces(),//参数二:目标类的接口类


    new InvocationHandler(){//参数三:Handler对象                 (此处参数用‘匿名内部类’!)

           //client程序调用objProxy.add("abc")方法时,就会去调用invoke方法,所以涉及三要素(即:invoke(objProxy对象、add方法、"abc"参数))
     public Object invoke(Object proxy, Method method, Object[] args)//在代理实例上处理方法调用并返回结果。在与方法关联的代理实例上调用方法时,将在调用处理程序上调用此方法
       throws Throwable {

       advice.beforeMethod(method);//切面方法(处理事务,日志等)(AOp思想)
      Object retVal = method.invoke(target, args);//对带有指定参数的指定对象调用由此 Method 对象表示的底层方法。(即调用目标类target中相对应的底层方法)
      advice.afterMethod(method);//切面方法(处理事务,日志等))(AOp思想)

      return retVal;      
      
     }
    }
    );
  return proxy3;
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值