[英]Check, if all classes in project have a specific annotation
My current situation: I want to write a test that checks, if all my files with "Service" in the name have the "@Valid" Annotation.我目前的情况:我想编写一个测试来检查我所有名称中带有“服务”的文件是否都具有“@Valid”注释。 I tried researching it but could not find anything.我尝试研究它,但找不到任何东西。
The Java Reflection API can be used to check the annotations of a class. Java 反射 API可用于检查 class 的注释。
Eg the following code prints the name and value of each class annotation of type MyAnnotation
.例如,以下代码打印 MyAnnotation 类型的每个MyAnnotation
注释的名称和值。
Class aClass = TheClass.class;
Annotation[] annotations = aClass.getAnnotations();
for(Annotation annotation : annotations){
if(annotation instanceof MyAnnotation){
MyAnnotation myAnnotation = (MyAnnotation) annotation;
System.out.println("name: " + myAnnotation.name());
System.out.println("value: " + myAnnotation.value());
}
}
The comment by Lino shows how to find all classes in the current classpath. Lino 的评论显示了如何在当前类路径中查找所有类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.