Java:获取私有成员的注释

Java:获取私有成员的注释,java,annotations,Java,Annotations,我试图找到所有带有自定义注释的字段,但它似乎没有检测到。同样的代码适用于标准注释,例如@Deprecated 要复制的最小代码: public class MyClass { public @interface MyAnnotation {} @MyAnnotation Object someObject; @MyAnnotation @Deprecated Object someDeprecatedObject; @Deprecated Object aTh

我试图找到所有带有自定义注释的字段,但它似乎没有检测到。同样的代码适用于标准注释,例如@Deprecated

要复制的最小代码:

public class MyClass {

    public @interface MyAnnotation {}

    @MyAnnotation Object someObject;
    @MyAnnotation @Deprecated Object someDeprecatedObject;
    @Deprecated Object aThirdObject;

    public static void main(String[] args) {
        Class<?> cls = MyClass.class;

        for (Field field : cls.getDeclaredFields()) {
            System.out.print(field.getName());

            for (Annotation a : field.getDeclaredAnnotations())
                System.out.print(" " + a);

            System.out.println();
        }
    }
}

@出现了弃用,但@MyAnnotation没有!救命啊

默认情况下,注释不会在运行时保留,因此无法反映出来。您需要像这样声明注释,以确保它在运行时存在:

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}