【问题标题】:Java: cannot access annotations through reflectionJava:无法通过反射访问注释
【发布时间】:2010-02-18 07:49:30
【问题描述】:

这是一个测试类:

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class TestAnnotations {

    @interface Annotate{}

    @Annotate public void myMethod(){}

    public static void main(String[] args) {
        try{
            Method[] methods = TestAnnotations.class.getDeclaredMethods();
            Method m = methods[1];
            assert m.getName().equals("myMethod");

            System.out.println("method inspected ? " + m.getName());
            Annotation a = m.getAnnotation(Annotate.class);
            System.out.println("annotation ? " + a);
            System.out.println("annotations length ? "
                + m.getDeclaredAnnotations().length);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}

这是我的输出:

method inspected ? myMethod
annotation : null
annotations length : 0

通过反射使注释可见我缺少什么?
即使只是检查它们的存在,我是否也需要注释处理器?

【问题讨论】:

    标签: java reflection annotations


    【解决方案1】:

    为了在运行时访问一个注解,它需要有一个运行时的保留策略。

    @Retention(RetentionPolicy.RUNTIME) @interface Annotate {}
    

    否则,注释会被删除,而 JVM 不知道它们。
    如需更多信息,请参阅here

    【讨论】:

    • 请问,如果您碰巧知道是否有办法将 CLASS 保留策略的默认行为更改为 RUNTIME ?
    • 只能通过重新编译注解。如果不是您的注释,则不会。
    猜你喜欢
    • 1970-01-01
    • 2020-11-15
    • 2011-09-19
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 2012-01-20
    • 2022-01-11
    • 2010-09-11
    相关资源
    最近更新 更多