0

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.

Civan Öner
  • 65
  • 1
  • 8
  • 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 Answers1

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());
    }
}

source

The comment by Lino shows how to find all classes in the current classpath.

TuurN
  • 11
  • 1
  • 1