How to scan classes for annotations?

loyalflow picture loyalflow · Oct 29, 2012 · Viewed 43.3k times · Source

I have a plain jane servlets web application, and some of my classes have the following annotations:

@Controller
@RequestMapping(name = "/blog/")
public class TestController {
..

}

Now when my servlet applications starts up, I would like to get a list of all classes that have the @Controller annotation, and then get the value of the @RequestMapping annotation and insert it in a dictionary.

How can I do this?

I'm using Guice and Guava also, but not sure if that has any annotation related helpers.

Answer

Jacob Schoen picture Jacob Schoen · Oct 29, 2012

You can use the Reflections library by giving it the package and Annotation you are looking for.

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

for (Class<?> controller : annotated) {
    RequestMapping request = controller.getAnnotation(RequestMapping.class);
    String mapping = request.name();
}

Of course placing all your servlets in the same package makes this a little easier. Also you might want to look for the classes that have the RequestMapping annotation instead, since that is the one you are looking to get a value from.