在java 8里面,注解一共有2个改进,一个是类型注解,在上篇已经介绍了,本篇将介绍另一个注解的改进:重复注解(JEP 120)。
java
容许在同一申明类型(类,属性,或方法)的屡次使用同一个注解 spa
java 8以前也有重复使用注解的解决方案,但可读性不是很好,好比下面的代码: .net
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里面的作法: code
@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里面作法更适合常规的思惟,可读性强一点 orm
JEP120没有太多内容,是一个小特性,仅仅是为了提升代码可读性。此次java 8对注解作了2个方面的改进(JEP 104,JEP120),相信注解会比之前使用得更加频繁了。 it
转载时候请注明出处。 http://my.oschina.net/benhaile io