如何通过JAVA反射处理注释的所有特性



我知道我们可以通过java反射来执行基于注释的类。

代码将执行带有@Test (TestNG框架)注释的方法。是否有可能处理该注释提供的功能?

如果可能,如何实现这些东西?

您可以使用getAnnotation而不是isAnnotationPresent获得注释(如果注释不存在,前者返回null),然后像任何其他Java对象一样访问其属性。

Test testAnnotation = method.getAnnotation(Test.class);
if (testAnnotation != null) {
  System.out.println(testAnnotation.priority());
}
for (Method me : method) {
    Annotation[] annotations = me.getDeclaredAnnotations(); //get Annotations associated with that method
  for(Annotation annotation : annotations){
      if(annotation instanceof Test){
          Test myAnnotation = (Test) annotation;
          System.out.println("priority: " + myAnnotation.priority());
          System.out.println("dependsOnMethod: " + myAnnotation.dependsOnMethod());
      }
    }
}

最新更新