getAnnotations()为空

Wal*_*uch 18 java annotations

我想在我的应用程序中使用注释.出于这个原因,我为注释创建了"hello world":

如下例子:

public class HelloAnnotation
{
    @Foo(bar = "Hello World !")
    public String str;

    public static void main(final String[] args) throws Exception
    {
        System.out.println(HelloAnnotation.class.getField("str").getAnnotations().length);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是注释:

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
public @interface Foo
{
    public String doTestTarget();
}
Run Code Online (Sandbox Code Playgroud)

我的问题是main中的getAnnotations()是空的.我的代码出了什么问题?

Dav*_*ant 40

将以下内容添加到注释中:

    @Retention(RetentionPolicy.RUNTIME)
Run Code Online (Sandbox Code Playgroud)

来自@Retention的javadoc :

保留策略默认为 RetentionPolicy.CLASS

RetentionPolicy的javadoc :

  • CLASS
    • 注释将由编译器记录在类文件中,但在运行时不需要由VM保留.
  • RUNTIME
    • 注释将由编译器记录在类文件中,并在运行时由VM保留,因此可以反射性地读取它们.
  • SOURCE
    • 编译器将丢弃注释.