如何获取不同注释的值

时间:2013-04-22 12:21:32

标签: java annotations

如何为不同的注释打印注释值?

我有以下两个注释

@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Author 
{
    String name() default "--Unknown--";
    String date() default "--Unknown--";
}

@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Revision 
{
    int version() default 0;
    String modifiedBy() default "--Unknown--";
}

现在一个类使用这个注释,在这个类中我想显示两个注释的注释值

@Author(
        name = "Panther",
        date = "22.04.2013"
        )

@Revision(
        version = 2,
        modifiedBy = "Black", 
        )
public class AnnotationTest
{
    public static void main(String[] args)
    {
        AnnotationTest b = new AnnotationTest();
        for(Annotation a : AnnotationTest.class.getDeclaredAnnotations())
        {
            // for Author display name and date
            // for revision display version and modifiedBy
        }
    }
}

有没有办法做到这一点?

2 个答案:

答案 0 :(得分:3)

您可以使用instanceof

for (Annotation a : AnnotationTest.class.getDeclaredAnnotations()) {
   if (a instanceof Author) {
      Author author = (Author) a;
      System.out.println("Author Name: " + author.name());
      System.out.println("Date: " + author.date());

   } else if (a instanceof Revision) {
      Revision revision = (Revision) a;
      System.out.println("Version: " + revision.version());
      System.out.println("Modified By: " + revision.modifiedBy());
   } 
}

答案 1 :(得分:1)

答案很简单:

a.getClass().getAnnotation(Author.class).name();

这是通用的,因此getAnnotation将返回您要求的类型,然后您可以直接获取字段。