Java 8新特性探究(5):重復(fù)注解
什么是重復(fù)注解
允許在同一申明類型(類,屬性,或方法)的多次使用同一個(gè)注解
一個(gè)簡(jiǎn)單的例子
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(){
- }
- }
由另一個(gè)注解來(lái)存儲(chǔ)重復(fù)注解,在使用時(shí)候,用存儲(chǔ)注解Authorities來(lái)擴(kuò)展重復(fù)注解,我們?cè)賮?lái)看看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時(shí),加上@Repeatable,指向存儲(chǔ)注解Authorities,在使用時(shí)候,直接可以重復(fù)使用Authority注解。從上面例子看出,java 8里面做法更適合常規(guī)的思維,可讀性強(qiáng)一點(diǎn)
總結(jié)
JEP120沒(méi)有太多內(nèi)容,是一個(gè)小特性,僅僅是為了提高代碼可讀性。這次java 8對(duì)注解做了2個(gè)方面的改進(jìn)(JEP 104,JEP120),相信注解會(huì)比以前使用得更加頻繁了。
原文鏈接:http://my.oschina.net/benhaile/blog/180932