如何获取类注解的java吗? [英] How to get class annotation in java?

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

问题描述

我已经创建了自己的注释类型是这样的:

I have created my own annotation type like this:

public @interface NewAnnotationType {}

和它连接到一个类:

@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?

推荐答案

默认保留策略是<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/RetentionPolicy.html#CLASS\"><$c$c>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.

相反,使用<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/RetentionPolicy.html#RUNTIME\"><$c$c>RetentionPolicy.RUNTIME:

注解要被记录在由编译器的类文件,并在运行时由VM保留,所以它们可以被反射性地读取。

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.

...您指定使用<$c$c>@Retention元注释

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

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

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

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