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.
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With