How to scan classes for annotations?

时光怂恿深爱的人放手 提交于 2019-12-30 01:51:13

问题


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.


回答1:


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.




回答2:


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.




回答3:


If you are using Spring,

It has something called a AnnotatedTypeScanner class.
This class internally uses

ClassPathScanningCandidateComponentProvider

This class has the code for actual scanning of the classpath resources. It does this by using the class metadata available at runtime.

One can simply extend this class or use the same class for scanning. Below is the constructor definition.

   /**
     * Creates a new {@link AnnotatedTypeScanner} for the given annotation types.
     * 
     * @param considerInterfaces whether to consider interfaces as well.
     * @param annotationTypes the annotations to scan for.
     */
    public AnnotatedTypeScanner(boolean considerInterfaces, Class<? extends Annotation>... annotationTypes) {

        this.annotationTypess = Arrays.asList(annotationTypes);
        this.considerInterfaces = considerInterfaces;
    }



回答4:


Try corn-cps

List<Class<?>> classes = CPScanner.scanClasses(new PackageNameFilter("net.sf.corn.cps.*"),new ClassFilter().appendAnnotation(Controller.class));
for(Class<?> clazz: classes){
   if(clazz.isAnnotationPresent(RequestMapping.class){
     //This is what you want
   }
}

Maven module dependency :

<dependency>
    <groupId>net.sf.corn</groupId>
    <artifactId>corn-cps</artifactId>
    <version>1.0.1</version>
</dependency>

visit the site https://sites.google.com/site/javacornproject/corn-cps for more information




回答5:


Instead of using reflection directly, you can make a lot easier for you by using AOP libraries from Google Guice. AOP is a common way for implementing cross-cutting concerns of an application, such as logging/tracing, transaction handling or permission checking.

You can read more about it here: https://github.com/google/guice/wiki/AOP




回答6:


If you can get access of your .class files, then you may get the annotation using the class as below:

  RequestMapping reqMapping =  
                         TestController.class.getAnnotation(RequestMapping.class);
  String name = reqMapping.name(); //now name shoud have value as "/blog/"

Also please make sure, your classes are marked with RetentionPolicy as RUNTIME

  @Retention(RetentionPolicy.RUNTIME)


来源:https://stackoverflow.com/questions/13128552/how-to-scan-classes-for-annotations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!