简体   繁体   中英

How to scan classes for custom Annotations?

I have my custom annotation and I want to scan all the classes for this annotation at runtime. What is the best way to do this? I'm not using Spring.

You could use the Reflections Library to determine the class names first and then use getAnnotations to check for the annotation:

Reflections reflections = new Reflections("org.package.foo");

Set<Class<? extends Object>> allClasses = 
                 reflections.getSubTypesOf(Object.class);


for (Class clazz : allClasses) {
   Annotation[] annotations = clazz.getAnnotations();

   for (Annotation annotation : annotations) {
     if (annotation instanceof MyAnnotation) {
        MyAnnotation myAnnotation = (MyAnnotation) annotation;
        System.out.println("value: " + myAnnotation.value());
     }
   }
}     

You might get annotations from the class using getClass().getAnnotations() or ask for a particular annotation if you don't want to loop over the results of the previous. In order for the annotation to appear on the result it's retention must be RUNTIME. For example (not strictly correct):

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyAnnotation {}

Check the Javadoc: Class#getAnnotation(Class)

And after that your class should be annotated like this:

@MyAnnotation public class MyClass {}    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM