2

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

我有以下两个注解

@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
        }
    }
}

有什么办法吗?

4

2 回答 2

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());
   } 
}
于 2013-04-22T12:27:00.597 回答
1

答案很简单:

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

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

于 2013-04-22T12:30:48.437 回答