一、什么是重復(fù)注解
允許在同一申明類型(類,屬性,或方法)的多次使用同一個注解
二、一個簡單的例子
java 8之前也有重復(fù)使用注解的解決方案,但可讀性不是很好,比如下面的代碼:
public @interface Authority {
String role();
}
public @interface Authorities {
Authority[] value();
}
public class RepeatAnnotationUseOldVersion {
@Authorities({@Authority(role="Admin"),@Authority(role="Manager")})
public void doSomeThing(){
}
}
由另一個注解來存儲重復(fù)注解,在使用時候,用存儲注解Authorities來擴展重復(fù)注解,我們再來看看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(){ }
}
不同的地方是,創(chuàng)建重復(fù)注解Authority時,加上@Repeatable,指向存儲注解Authorities,在使用時候,直接可以重復(fù)使用Authority注解。從上面例子看出,java 8里面做法更適合常規(guī)的思維,可讀性強一點
三、總結(jié)
JEP120沒有太多內(nèi)容,是一個小特性,僅僅是為了提高代碼可讀性。這次java 8對注解做了2個方面的改進(JEP 104,JEP120),相信注解會比以前使用得更加頻繁了。