我想在我的应用程序中使用注释.出于这个原因,我为注释创建了"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
RUNTIME
SOURCE