run time annotation scanning when Dynamic class loading

主宰稳场 提交于 2019-12-08 07:04:32

问题


import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

// declare a new annotation
@Retention(RetentionPolicy.RUNTIME)
@interface Demo {
   String str();
   int val();
}

public class PackageDemo {

   // set values for the annotation
   @Demo(str = "Demo Annotation", val = 100)
   // a method to call in the main
   public static void example() {
      PackageDemo ob = new PackageDemo();

      try {
         Class c = ob.getClass();

         // get the method example
         Method m = c.getMethod("example");

         // get the annotation for class Demo
         Demo annotation = m.getAnnotation(Demo.class);

         // print the annotation
         System.out.println(annotation.str() + " " + annotation.val());
      } catch (NoSuchMethodException exc) {
         exc.printStackTrace();
      }
   }
   public static void main(String args[]) {
      example();
   }
}

My objective is to check the annotation on few methods and if it exists on the annotation , I need to get the annotation.

Demo annotation = m.getAnnotation(Demo.class);

In the above example , the annotation is declared in the same file. If annotation is in a different package I can do something like

import com.this.class.DemoClass
try {
         Class c = ob.getClass();

         // get the method example
         Method m = c.getMethod("example");

         // get the annotation for class Demo
         Demo annotation = m.getAnnotation(Demo.class);

But if I want to load the DemoClass/AnnotationClass dynamically like

Class<?> Demo = Class.forName("com.this.class.DemoClass")

How do I get the annotation on the methods. I think the below line doesn't works in this case

Demo annotation = m.getAnnotation(Demo.class);

回答1:


This approach worked for me. hope this helps someone.

 DemoClass= (Class<Annotation>) Class.forName("com.this.class.DemoClass");
    if (method.isAnnotationPresent(DemoClass)) {
       for (Annotation annotation : method.getAnnotations()) {
       Class<? extends Annotation> annotationType = annotation.annotationType();      
       if (annotationType.getName() == "com.this.class.DemoClass") {
          for (Method annotationMethod : annotationType.getDeclaredMethods()) {
          value= annotationMethod.invoke(annotation, (Object[]) null);
          }
       }
     }



回答2:


When the annotation is loaded dynamically into variable, Demo, then use that variable to get the annotation:

Class<?> Demo = Class.forName("com.this.class.DemoClass");
Demo annotation = m.getAnnotation(Demo);


来源:https://stackoverflow.com/questions/47662984/run-time-annotation-scanning-when-dynamic-class-loading

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