如何在java中获取类注释? [英] How to get class annotation in java?

查看:91
本文介绍了如何在java中获取类注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created my own annotation type like this:

public @interface NewAnnotationType {}

并将其附加到一个类中:

and attached it to a class:

@NewAnnotationType
public class NewClass {
    public void DoSomething() {}
}

我试图通过这样的反射来获取类注释:

and I tried to get the class annotation via reflection like this :

Class newClass = NewClass.class;

for (Annotation annotation : newClass.getDeclaredAnnotations()) {
    System.out.println(annotation.toString());
}

但它没有打印任何东西.我做错了什么?

but it's not printing anything. What am I doing wrong?

推荐答案

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

The default retention policy is RetentionPolicy.CLASS which means that, by default, annotation information is not retained at runtime:

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

Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time. This is the default behavior.

改为使用 RetentionPolicy.RUNTIME:

注解会被编译器记录在类文件中,并在运行时由虚拟机保留,因此可以反射读取.

Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.

...您使用 @Retention 指定 元注解:

...which you specify using the @Retention meta-annotation:

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

这篇关于如何在java中获取类注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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