My current situation: I want to write a test that checks, if all my files with "Service" in the name have the "@Valid" Annotation. I tried researching it but could not find anything.
Asked
Active
Viewed 302 times
0
-
Related: [Can you find all classes in a package using reflection?](https://stackoverflow.com/questions/520328/can-you-find-all-classes-in-a-package-using-reflection) – Lino Jan 25 '21 at 14:40
1 Answers
1
The Java Reflection API can be used to check the annotations of a class.
E.g. the following code prints the name and value of each class annotation of type 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.

TuurN
- 11
- 1
- 1