一、什麼是重複註解
允許在同一申明類型(類,屬性,或方法)的多次使用同一個註解
二、一個簡單的例子
java 8之前也有重複使用註解的解決方案,但可讀性不是很好,例如下面的程式碼:
複製代碼代碼如下:
public @interface Authority {
String role();
}
public @interface Authorities {
Authority[] value();
}
public class RepeatAnnotationUseOldVersion {
@Authorities({@Authority(role="Admin"),@Authority(role="Manager")})
public void doSomeThing(){
}
}
由另一個註解來儲存重複註解,在使用時候,用儲存註解Authorities來擴充重複註解,我們再來看看java 8裡面的做法:
複製代碼代碼如下:
@Repeatable(Authorities.class)
public @interface Authority {
String role();
}
public @interface Authorities {
Authority[] value();
}
public class RepeatAnnotationUseNewVersion {
@Authority(role="Admin")
@Authority(role="Manager")
public void doSomeThing(){ }
}
不同的地方是,創建重複註解Authority時,加上@Repeatable,指向儲存註解Authorities,在使用時候,直接可以重複使用Authority註解。從上面例子看出,java 8裡面做法比較適合常規的思維,可讀性強一點
三、總結
JEP120沒有太多內容,是一個小特性,只是為了提高程式碼可讀性。這次java 8對註解做了2個方面的改進(JEP 104,JEP120),相信註解會比以前使用得更加頻繁了。