查找带注释的注释

有一个注释@MarkerAnnotation 。 它可以直接添加到方法中。 或任何其他注释,如

 @MarkerAnnotation @Interface CustomAnnotation {...} 

这个@CustomAnnotation也可以直接添加到方法中。 这是许多框架允许用户添加自己的注释(例如spring)的标准方式。

现在,给定一个类,我想找到所有用@MarkerAnnotation直接或间接标记的方法。 对于每个方法,我还想找到相关的@MarkerAnnotation和/或@CustomAnnotation 。 有没有我可以使用的工具,或者我必须手动完成它?

Spring在他们的核心项目中有一个AnnotationUtils类,它可以满足您的需求。 findAnnotation的javadoc:

如果注释不直接出现在给定方法本身上,则在提供的方法上查找annotation注释类型,遍历其超级方法(即,从超类和接口)。 正确处理编译器生成的桥接方法。

如果注释不直接出现在方法上,则将搜索元注释。

默认情况下,方法的注释不会inheritance,因此我们需要显式处理。

对于通用方法,您应该使用javac的注释处理器工具,它要求您编写一个注释处理器,该处理器使用包javax.annotation.processingjavax.lang.model及其子包javax.annotation.processing的API。 此代码将在javac运行。 (有一个较旧的工具apt ,它与javac是分开的,但在Java 7中不推荐使用apt 。)

特别是,当您访问每个Element ,可以在其上调用getAnnotationMirrors 。 然后,对于每个注释,调用getAnnotationType().asElement()以获取注释类型的Element 。 如果可能存在多个间接级别,则可能需要使用递归来查找间接注释。

比如这样……

 public class Test{ @MarkerAnnotation public void TestMethod1(){ } @CustomAnnotation @MarkerAnnotation public void TestMethod2(){ } } 

你可以像这样解析..

 public class AnnotationTest{ public static void main(String[] args){ Method[] methods = Test.class.getDeclaredMethods(); for(Method method: methods){ Annotation[] annotations = method.getAnnotations(); for(Annotation annotation: annotations){ if(annotation instanceof MarkerAnnotation) System.out.println(method.getName() +" annotated with MarkerAnnotation"); if(annotation instanceof CustomAnnotation) System.out.println(method.getName() +" annotated with CustomAnnotation"); } } } } 

如果你想检查CustomAnnotation有MarkerAnnotation,那么这样做..

  if(CustomAnnotation.class.isAnnotation()){ Annotation[] annotations = CustomAnnotation.class.getAnnotations(); if(annotations[0] instanceof MarkerAnnotation){ System.out.println("CustomAnnotation have MarkerAnnotation"); } }