Java重复注释
示例
在Java8之前,不能将同一注释的两个实例应用于单个元素。标准的解决方法是使用包含其他批注数组的容器批注:
//作者.java
@Retention(RetentionPolicy.RUNTIME)
public @interface Author {
String value();
}
//作者.java
@Retention(RetentionPolicy.RUNTIME)
public @interface Authors {
Author[] value();
}
//Test.java
@Authors({
@Author("Mary"),
@Author("Sam")
})
public class Test {
public static void main(String[] args) {
Author[] authors = Test.class.getAnnotation(Authors.class).value();
for (Author author : authors) {
System.out.println(author.value());
//输出:
//玛丽
//山姆
}
}
}Java8使用注释提供了一种更干净,更透明的容器注释使用方式@Repeatable。首先,我们将其添加到Author类中:
@Repeatable(Authors.class)
这告诉Java将多个@Author注释视为被@Authors容器包围。我们还可以通过其自己的类而不是通过其容器来访问数组:Class.getAnnotationsByType()@Author
@Author("Mary")
@Author("Sam")
public class Test {
public static void main(String[] args) {
Author[] authors = Test.class.getAnnotationsByType(Author.class);
for (Author author : authors) {
System.out.println(author.value());
//输出:
//玛丽
//山姆
}
}
}