zoukankan      html  css  js  c++  java
  • Java8新特性之重复注解(repeating annotations)

    一、什么是重复注解

    允许在同一申明类型(类,属性,或方法)的多次使用同一个注解

    二、一个简单的例子

    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),相信注解会比以前使用得更加频繁了。

  • 相关阅读:
    easyUI之tree
    MSSQL索引优化
    MongoDB学习笔记(一) MongoDB介绍及安装
    项目经理必备的11种人际关系技能
    http协议详细介绍
    ERP存储过程
    UVA1339 UVALive3213 POJ2159 ZOJ2658 Ancient Cipher【密码】
    UVA1588 UVALive3712 POJ3158 Kickdown
    UVA1588 UVALive3712 POJ3158 Kickdown
    UVA10340 POJ1936 ZOJ1970 All in All【字符串匹配】
  • 原文地址:https://www.cnblogs.com/exmyth/p/11387701.html
Copyright © 2011-2022 走看看