How to scan classes for annotations?

前端 未结 7 2063
野性不改
野性不改 2020-12-28 17:00

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

@Controller
@RequestMapping(name = \"/blog/\")
public cl         


        
相关标签:
7条回答
  • 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;
        }
    
    0 讨论(0)
  • 2020-12-28 17:42

    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.

    0 讨论(0)
  • 2020-12-28 17:52

    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.

    0 讨论(0)
  • 2020-12-28 17:52

    The following code worked for me, the below example uses Java 11 and spring ClassPathScanningCandidateComponentProvider. The usage is to find all classes annotated with @XmlRootElement

    public static void main(String[] args) throws ClassNotFoundException {
        var scanner = new ClassPathScanningCandidateComponentProvider(false);
        scanner.addIncludeFilter(new AnnotationTypeFilter(XmlRootElement.class));
    
        //you can loop here, for multiple packages
        var beans = scanner.findCandidateComponents("com.example");
        for (var bean : beans) {
            var className = bean.getBeanClassName();
            Class clazz = Class.forName(className);
            //creates initial JAXBContext for later usage
            //JaxbContextMapper.get(clazz);
            System.out.println(clazz.getName());
        }
    }
    
    0 讨论(0)
  • 2020-12-28 18:03

    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

    0 讨论(0)
  • 2020-12-28 18:03

    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)
    
    0 讨论(0)
提交回复
热议问题