Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scan classes for annotations?

Tags:

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.

like image 482
loyalflow Avatar asked Oct 29 '12 19:10

loyalflow


People also ask

How do you know if a class is annotated?

The isAnnotation() method is used to check whether a class object is an annotation. The isAnnotation() method has no parameters and returns a boolean value. If the return value is true , then the class object is an annotation.

Can classes be annotated?

Annotations help to associate metadata (information) to the program elements i.e. instance variables, constructors, methods, classes, etc. Annotations are not pure comments as they can change the way a program is treated by the compiler.

What is the annotation process?

Annotating is any action that deliberately interacts with a text to enhance the reader's understanding of, recall of, and reaction to the text. Sometimes called "close reading," annotating usually involves highlighting or underlining key pieces of text and making notes in the margins of the text.

How do annotation processors work?

An annotation processor processes these annotations at compile time or runtime to provide functionality such as code generation, error checking, etc. The java. lang package provides some core annotations and also gives us the capability to create our custom annotations that can be processed with annotation processors.


2 Answers

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.

like image 176
Jacob Schoen Avatar answered Oct 12 '22 07:10

Jacob Schoen


Scanning for annotations is very difficult. You actually have to process all classpath locations and try to find files that correspond to Java classes (*.class).

I strongly suggest to use a framework that provides such functionality. You could for example have a look at Scannotation.

like image 38
chkal Avatar answered Oct 12 '22 05:10

chkal