文章目錄
- 1. 前言
- 2. 先說結論
- 3. 案例演示
1. 前言
- 最近無意看到某些注解上有@Repeatable,出于比較好奇,因此稍微研究并寫下此文章。
2. 先說結論
-
@Repeatable的作用:使被他注釋的注解可以在同一個地方重復使用。
-
具體使用如下:
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Repeatable(value = MyAnnotationList.class) public @interface MyAnnotation {String name(); }@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotationList {// 被 @Repeatable引用的注解中,必須得有被 @Repeatable注釋的注解(@MyAnnotation)返回類型的value方法MyAnnotation[] value(); }public class MyAnnotationTest {@MyAnnotation(name = "Test1")@MyAnnotation(name = "Test2")private void testMethod() {}@MyAnnotationList(value = {@MyAnnotation(name = "Test1"), @MyAnnotation(name = "Test2")})private void testMethod2() {} }
3. 案例演示
-
先定義新注解
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation {String name(); }
-
創建新類并使用自定義注解
public class MyAnnotationTest {@MyAnnotation(name = "Test1")private void testMethod(){} }
-
當注解@MyAnnotation還沒被@Repeatable注釋的時候,在testMethod()方法上使用多次,會出現下面報錯:
將會提示:@MyAnnotation沒被@Repeatable注解,無法重復使用@MyAnnotation -
因此在@MyAnnotation上使用@MyAnnotation,如下:
@Repeatable(value = MyAnnotationList.class) 中引用了 @MyAnnotationList注解,用于@MyAnnotation注解上,有如下幾個細節:-
細節一:在引用注解上的@MyAnnotationList的方法中得有value()方法,如下:
-
細節二:在引用注解上的@MyAnnotationList的方法中得有【被@Repeatable注解的@MyAnnotation注解類型的數組返回值的value方法】
-
細節三:該案例中,若在方法上重復使用@MyAnnotation注解,實際上也會在運行的時候被包裝成MyAnnotationList[] 里面,如下:
-
細節四:@MyAnnotation可多次使用,但不可多次與@MyAnnotationList一起使用,如下:
-
細節五:@MyAnnotation可多次使用,但僅可一個與@MyAnnotationList一起使用,但唯一的@MyAnnotation在運行的時候被包裝成MyAnnotationList[] 里面,如下:
-