gpt4 book ai didi

java - 如何从jar文件中的类中获取注释的参数

转载 作者:行者123 更新时间:2023-12-01 09:00:54 25 4
gpt4 key购买 nike

我想通过java Reflect获取一个类(打包在jar文件中)的注解参数。

  1. 我的注释是这样的

    @Documented
    @Retention(RUNTIME)
    @Target(TYPE)
    public @interface TestPlugin {
    public String moduleName();
    public String plugVersion();
    public String minLeapVersion();
    }
  2. 我的类(class)是这样的

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

    Debug windows info

最佳答案

由于某些技术原因,Java VM 使用的“真正”注释类是动态代理。这不应该打扰你。他们仍然“实现”您的注释类。只需使用

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

编辑:刚刚在 another answer 中找到,您也可以在循环中询问 anno 对象,但不要使用 getClass()。使用.annotationType()

关于java - 如何从jar文件中的类中获取注释的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41676464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com