重复注解
用@Repeatable标记的注解可以在注解目标类型上重复添加该注解。
java
@Test("test1")
@Test("test2")
public class RepeatAnnotationTest {
public static void main(String[] args) {
Test[] tests = RepeatAnnotationTest.class.getAnnotationsByType(Test.class);
assert tests.length == 2;
Tests annotation = RepeatAnnotationTest.class.getAnnotation(Tests.class);
assert annotation != null && annotation.value().length == 2;
IntStream.range(0, 2)
.forEach(it -> {
assert tests[it].equals(annotation.value()[it]);
});
Test test = RepeatAnnotationTest.class.getAnnotation(Test.class);
assert Objects.isNull(test);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
java
@Repeatable(Tests.class)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {
String value();
}
1
2
3
4
5
6
2
3
4
5
6
java
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Tests {
Test[] value();
}
1
2
3
4
5
6
2
3
4
5
6