Skip to content

How to scan for annotations in methods only in specific classes using reflection library java?

I have an annotation @API which I assign to all the routes i.e RequestMapping in a controller in java spring.What I want to do is,First scan all the classes in a package that are annotated with @Controller and after scanning all the controller classes,I want only to scan for Methods with annotation @API in only these controller annotated classes.

How can I implement this in using reflection in java?

  Reflections reflections = new Reflections("my.project.prefix");

  Set<Class<? extends SomeType>> subTypes = reflections.getSubTypesOf(SomeType.class);

Answer

To find the classes containing the @Controller annotation in a package using the reflection api, you can try:

Reflections reflections = new Reflections("my.project.prefix");
Set<Class<?>> classes = reflections
        .getTypesAnnotatedWith(Controller.class);

To find the methods that contain the @API annotation in a package using the reflection api, you can try:

Reflections reflections = new Reflections("my.project.prefix");
Set<Method> methods = reflections
        .getMethodsAnnotatedWith(API.class);

If you want to find methods with @API annotation inside classes that contain only @Controller annotation, you’ll need to write code similar to this:

Reflections reflections = new Reflections("my.project.prefix");
Set<Class<?>> classes = reflections
        .getTypesAnnotatedWith(Controller.class);
for (Class<?> clazz : classes) {
    Method[] methods = clazz.getDeclaredMethods();
    for (Method method : methods) {
        Annotation[] annotations = method.getDeclaredAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation instanceof API) {
                // ..
            }
        }
    }
}