开发者

Java: cannot access annotations through reflection

开发者 https://www.devze.com 2022-12-20 17:59 出处:网络
Here is a test class: import java.lang.annotation.Annotation; import java.lang.reflect.Method; public class TestAnnotations {

Here is a test class:

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();
        }
    }
}

Here is my output :

method inspected ? myMethod
annotatio开发者_运维百科n : 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 ?


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

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消