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

  • 相关阅读:
    <整理> 在Bash中添加个人定制的命令
    <整理> linux常用命令及工具
    论文分享:目标检测-YOLO
    Siamese Attentional Keypoint Network for High Performance Visual Tracking--论文笔记
    ubuntu 相关软件设置
    anoconda 神经网络 相关操作
    转载:决策树算法梳理
    转载:XGBOOST算法梳理
    XGB算法梳理
    决策树算法梳理
  • 原文地址:https://www.cnblogs.com/exmyth/p/11387701.html
Copyright © 2011-2022 走看看