getAnnotations() 为空 [英] getAnnotations() is empty

查看:69
本文介绍了getAnnotations() 为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如下示例:

公共类HelloAnnotation{@Foo(bar = "你好世界!")公共字符串str;public static void main(final String[] args) 抛出异常{System.out.println(HelloAnnotation.class.getField("str").getAnnotations().length);}}

这是注释:

import java.lang.annotation.ElementType;导入 java.lang.annotation.Target;@Target(ElementType.FIELD)公共@interface Foo{公共字符串 doTestTarget();}

我的问题是现在 main 中的 getAnnotations() 是空的.我的代码有什么问题?

解决方案

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

 @Retention(RetentionPolicy.RUNTIME)

来自 @Retention 的 javadoc:><块引用>

保留策略默认为 RetentionPolicy.CLASS

来自 RetentionPolicy 的 javadoc:

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

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?

解决方案

Add the following to your annotation:

    @Retention(RetentionPolicy.RUNTIME)

From the javadoc for @Retention:

the retention policy defaults to RetentionPolicy.CLASS

From the javadoc for RetentionPolicy:

  • CLASS
    • Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time.
  • 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.
  • SOURCE
    • Annotations are to be discarded by the compiler.

这篇关于getAnnotations() 为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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