如何通过JAVA反射处理一个注解的所有特征
How to process all the features of an annotation through JAVA Reflection
我知道我们可以通过 java 反射根据注释执行 class。
该代码将执行一个用 @Test
(TestNG 框架) 注释的方法。是否可以处理该注释可用的功能?
如果可以,如何实现?
您可以使用 getAnnotation
而不是 isAnnotationPresent
获取注释(如果注释不存在,前者 returns 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());
}
}
}
我知道我们可以通过 java 反射根据注释执行 class。
该代码将执行一个用 @Test
(TestNG 框架) 注释的方法。是否可以处理该注释可用的功能?
如果可以,如何实现?
您可以使用 getAnnotation
而不是 isAnnotationPresent
获取注释(如果注释不存在,前者 returns 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());
}
}
}