java8對註解提供了兩點改進:
- 可重複的註解
- 可用於類型的註解
可重複的註解
先定義一個註解
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnno {
String value() default "";
}
此時在成員變量上定義兩個註解會報錯
@MyAnno("哈哈")
@MyAnno("heh")
public void name(){
}
報錯內容:Duplicate annotation. The declaration of 'repeatAnnotation.MyAnno' does not have a valid java.lang.annotation.Repeatable annotation
如何定義重複註解?
-
先定義一個父容器容器
-
用MyAnno作爲變量類型,聲明一個數組
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE}) @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnos{ MyAnno[] value(); }
-
然後把原來註解上加個新註解@Repeatable,入參父容器類對象
@Repeatable(value = MyAnnos.class) @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE}) @Retention(RetentionPolicy.RUNTIME) public @interface MyAnno { String value() default ""; }
-
此時就不報錯了
@MyAnno("哈哈") @MyAnno("heh") public void name(){ }
-
獲取註解內容
由於設置了@Retention(RetentionPolicy.RUNTIME),所以可以通過反射獲取註解值
@Test public void test() throws NoSuchMethodException { Class<demo> clazz = demo.class; //獲取目標類的Class對象 Method name = clazz.getMethod("name"); MyAnno[] annos = name.getAnnotationsByType(MyAnno.class); for (MyAnno anno : annos) { System.out.println("anno = " + anno.value()); } } /* 結果: anno = 哈哈 anno = heh */
類型的註解
-
多了一個 TYPE_PARAMETER
@Repeatable(value = MyAnnos.class)
@Target({
TYPE, FIELD, METHOD, PARAMETER,
CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER}
)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnno {
String value() default "";
}