在Dynamic Proxy中取方法标注(annotations)要注意的问题

来源:互联网 发布:js给body添加元素 编辑:程序博客网 时间:2024/05/01 08:15

在jdk1.5中对类的方法申明了标注(annotations),当使用动态代理对该类的实例进行代理后要在invoke(Object proxy, Method method, Object[] args)中获取方法method的标注时不能直接从method获取,就象下面的代码:

public class DynaProxy implements InvocationHandler {
 MyClass a = null;
 public DynaProxy(MyClass a) {
  // a 为被代理的对象  
  this.a = a;
 }
 
 public Object invoke(Object proxy, Method method, Object[] args)
   throws Throwable {
    

     // MyAnnotation 为标注,并且在MyClass的方法上申明

      MyAnnotation ann = method.getAnnotation(MyAnnotation.class);

      System.out.println(ann);      // 这时ann = null

   
      return method.invoke(a,args);
   }

}

 

而要使用下面的代码,从被代理的对象得到方法,在得到标注信息,

public class DynaProxy implements InvocationHandler {
 MyClass a = null;
 public DynaProxy(MyClass a) {
  // a 为被代理的对象  
  this.a = a;
 }
 
 public Object invoke(Object proxy, Method method, Object[] args)
   throws Throwable {
    

     // MyAnnotation 为标注,并且在MyClass的方法上申明

      MyAnnotation ann = a.getMethod(method.getName(),method.getParameterTypes()).getAnnotation(MyAnnotation.class);

      System.out.println(ann);      // 如果MyClass的被调用的方法申明了标注,可以被得到

   
      return method.invoke(a,args);
   }

}

 另外,如果使用CGlib来动态代理对象, 测试过2.1.3版本不能得到被代理对象的任何标注信息.

原创粉丝点击