วิธีรับพารามิเตอร์ของคำอธิบายประกอบจากคลาสในไฟล์ jar

ฉันต้องการรับพารามิเตอร์คำอธิบายประกอบของคลาส (บรรจุในไฟล์ jar) โดย javaสะท้อน

  1. คำอธิบายประกอบของฉันเช่นนี้

    @Documented
    @Retention(RUNTIME)
    @Target(TYPE)    
    public @interface TestPlugin {
        public String moduleName();
        public String plugVersion();
        public String minLeapVersion();    
    }
    
  2. ชั้นเรียนของฉันเป็นแบบนี้

    @TestPlugin(moduleName="xxx", plugVersion="1.0.0", minLeapVersion="1.3.0")
    
    public class Plugin {
    
      ......
    
    }
    
  3. รหัสการเข้าถึงของฉันเช่นนี้

    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?
        */
    }
    

    แก้ไขข้อบกพร่องข้อมูลหน้าต่าง


person Robbie    schedule 16.01.2017    source แหล่งที่มา
comment
หน้าต่างแก้ไขข้อบกพร่องสามารถพบได้ในรูปภาพที่แนบมา   -  person Robbie    schedule 16.01.2017


คำตอบ (1)


คลาสคำอธิบายประกอบ "ของจริง" ที่ใช้โดย Java VM คือ Dynamic Proxies ด้วยเหตุผลทางเทคนิคบางประการ สิ่งนี้ไม่ควรรบกวนคุณ พวกเขายังคง "ใช้งาน" คลาสคำอธิบายประกอบของคุณ เพียงแค่ใช้

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

แก้ไข: เพิ่งพบในคำตอบอื่นที่คุณสามารถถามวัตถุ anno ของคุณในลูปของคุณได้ แต่อย่าใช้ getClass() ใช้ .annotationType()

person Florian Albrecht    schedule 16.01.2017