如何在java中获取类注释?

Joh*_*ith 40 java reflection annotations

我创建了自己的注释类型,如下所示:

public @interface NewAnnotationType {}
Run Code Online (Sandbox Code Playgroud)

并将其附加到班级:

@NewAnnotationType
public class NewClass {
    public void DoSomething() {}
}
Run Code Online (Sandbox Code Playgroud)

我尝试通过这样的反射得到类注释:

Class newClass = NewClass.class;

for (Annotation annotation : newClass.getDeclaredAnnotations()) {
    System.out.println(annotation.toString());
}
Run Code Online (Sandbox Code Playgroud)

但它不打印任何东西.我究竟做错了什么?

Mat*_*all 49

默认保留策略RetentionPolicy.CLASS意味着,默认情况下,注释信息不会在运行时保留:

注释将由编译器记录在类文件中,但在运行时不需要由VM保留.这是默认行为.

相反,使用RetentionPolicy.RUNTIME:

注释将由编译器记录在类文件中,并在运行时由VM保留,因此可以反射性地读取它们.

...使用@Retention元注释指定的... :

@Retention(RetentionPolicy.RUNTIME)
public @interface NewAnnotationType {
}
Run Code Online (Sandbox Code Playgroud)