【问题标题】:Reflection can not find annotation反射找不到注解
【发布时间】:2014-05-27 09:10:30
【问题描述】:

我无法获得 bean 的注释,我正在使用 spring 框架:

可运行的测试类:

public class Main {

    public static void main(String[] args) {
        PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(Test.class,"foo");
        Method m=pd.getReadMethod();
        System.out.println(m.isAnnotationPresent(Annot.class));
    }

}

豆类;

public class Test {

    private String foo;

        @Annot
        public String getFoo() {
            return foo;
        }

        public void setFoo(String foo) {
            this.foo = foo;
        }

    }

注解类:

public @interface Annot {

}

主类得到“false”作为输出...为什么?

【问题讨论】:

标签: java spring annotations


【解决方案1】:

您的注释缺少运行时保留政策。

执行以下操作:

@Retention(RetentionPolicy.RUNTIME)
public @interface Annot {

}

查看this SO 问题,该问题解释了默认策略及其作用。 总结该答案中的信息,默认保留策略是CLASS,这意味着注释在字节码中,但在加载类时不必保留

【讨论】:

    猜你喜欢
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多