0

I want to get a class's (packaged in jar file) annotation parameters by java reflect.

  1. My annotation like this

    @Documented
    @Retention(RUNTIME)
    @Target(TYPE)    
    public @interface TestPlugin {
        public String moduleName();
        public String plugVersion();
        public String minLeapVersion();    
    }
    
  2. My class like this

    @TestPlugin(moduleName="xxx", plugVersion="1.0.0", minLeapVersion="1.3.0")
    
    public class Plugin {
    
      ......
    
    }
    
  3. My access code like this

    Class<?> clazz = this.loadClass(mainClassName);  // myself classloader
    
    Annotation[] annos = clazz.getAnnotations();
    
    for (Annotation anno : annos) {
        Class<? extends Annotation> annoClass = anno.annotationType();
    
        /* Question is here
        This code can get right annotationType: @TestPlugin. 
        Debug windows show anno is $Proxy33. 
        But I can't find any method to get annotation membervalues even though I can find them in debug windows.
        How can I get annotation's parameters?
        */
    }
    

    Debug windows info

abpatil
  • 916
  • 16
  • 20
Robbie
  • 3
  • 2

1 Answers1

1

The "real" annotation classes used by the Java VM are Dynamic Proxies for some technical reasons. This shouldn't bother you. They still "implement" your annotation class. Just use

TestPlugin plugin = clazz.getAnnotation(TestPlugin.class);

plugin.getClass() == TestPlugin.class; // false - is Dynamic proxy
TestPlugin.class.isAssignableFrom(plugin.getClass()); // true - Dynamic proxy implements TestPlugin interface

EDIT: Just found in another answer, that you could also ask your anno object in your loop, but do not use getClass(). Use .annotationType().

Community
  • 1
  • 1
Florian Albrecht
  • 2,266
  • 1
  • 20
  • 25