20230710 java.lang.annotation.Repeatable

发布时间 2023-08-24 10:27:24作者: 流星<。)#)))≦

介绍

  • java.lang.annotation.Repeatable
  • 声明
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Repeatable
  • 元注解
  • 指明这个注解可以在同一个项上应用多次
  • 为了向后兼容,可重复注解的实现者需要提供一个容器注解,它可以将这些重复注解存储到一个数组中
  • 在处理可重复注解时必须非常仔细。如果调用 getAnnotation 来查找某个可重复注解,而该注解又确实重复了,那么就会得到 null 。这是因为重复注解放包装到了容器注解中。
  • 在这种情况下,应该调用 getAnnotationsByType 。这个调用会“遍历”容器,并给出一个重复注解的数组。如果只有一条注解,那么该数组的长度就为 1 。通过使用这个方法,你就不用操心如何处理容器注解了

API

  • Class<? extends Annotation> value();
    • 返回对应的容器注解接口

代码示例

@Repeatable(TestCases.class)
@Retention(RUNTIME)
@Target(TYPE)
public @interface TestCase {
    String params() default "";
}


@Retention(RUNTIME)
@Target(TYPE)
public @interface TestCases {
    TestCase[] value();
}


@TestCase(params = "p1")
@TestCase(params = "p2")
public class MyCase {
}


public class MyMain {
    public static void main(String[] args) {
        Class<MyCase> myCaseClass = MyCase.class;
        System.out.println(Arrays.toString(myCaseClass.getAnnotations()));  // [@v2ch08.test.TestCases(value=[@v2ch08.test.TestCase(params=p1), @v2ch08.test.TestCase(params=p2)])]
        TestCase testCase = myCaseClass.getAnnotation(TestCase.class);
        System.out.println(testCase);     // null
        TestCase[] annotationsByType = myCaseClass.getAnnotationsByType(TestCase.class);
        System.out.println(Arrays.toString(annotationsByType));     // [@v2ch08.test.TestCase(params=p1), @v2ch08.test.TestCase(params=p2)]
        TestCases testCases = myCaseClass.getAnnotation(TestCases.class);
        System.out.println(testCases);     // @v2ch08.test.TestCases(value=[@v2ch08.test.TestCase(params=p1), @v2ch08.test.TestCase(params=p2)])

        System.out.println("==========");
        for (TestCase tc : testCases.value()) {
            System.out.println(tc.params());
        }
        /*
            p1
            p2
         */
    }
}