run time annotation scanning when Dynamic class lo

2019-06-08 03:21发布

问题:

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);