19

I would like to use annotations in my application. For this reason I create "hello world" for annotations:

follows example:

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);
    }
}

And this is the Annotation:

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

@Target(ElementType.FIELD)
public @interface Foo
{
    public String doTestTarget();
}

My problem is now that getAnnotations() in main is empty. What is wrong with my code?

4

1 回答 1

43

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

    @Retention(RetentionPolicy.RUNTIME)

来自@Retention的javadoc :

保留策略默认为RetentionPolicy.CLASS

来自RetentionPolicy的 javadoc :

  • CLASS
    • 注释将由编译器记录在类文件中,但不需要在运行时由 VM 保留
  • RUNTIME
    • 注释将由编译器记录在类文件中,并在运行时由 VM 保留,因此可以反射性地读取它们
  • SOURCE
    • 注释将被编译器丢弃。
于 2012-09-28T14:48:56.380 回答