Java:无法通过反射访问注释 [英] Java: cannot access annotations through reflection

查看:28
本文介绍了Java:无法通过反射访问注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个测试类:

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

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

What I am missing to make annotations visible through reflection ?
Do I need an annotation processor even for just checking their presence ?

推荐答案

为了在运行时访问一个注解,它需要有一个 Runtime 的 Retention 策略.

In order to access an annotation at runtime, it needs to have a Retention policy of Runtime.

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

否则,注解会被删除,JVM 不知道它们.
有关详细信息,请参阅此处.

Otherwise, the annotations are dropped and the JVM is not aware of them.
For more information, see here.

这篇关于Java:无法通过反射访问注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆