重复注解

简介: 重复注解

英雄非无泪,不洒敌人前。男儿七尺躯,愿为祖国捐。——陈辉

在java中如果我们需要一个注解能被重复使用

例如这个

package com.ruben.annotation;
import java.lang.annotation.*;
/**
 * @ClassName: BeanFieldSort
 * @Description:
 * @Date: 2020/9/11 22:18
 * *
 * @author: achao<achao1441470436 @ gmail.com>
 * @version: 1.0
 * @since: JDK 1.8
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BeanFieldSort {
    /**
     * 序号
     *
     * @return
     */
    int order();
}

如果我们直接重复注解,会发现编译错误

我们需要在注解上加上@Repeatable注解,里面参数放另外一个注解,作为它的承载

package com.ruben.annotation;
import java.lang.annotation.*;
/**
 * @ClassName: BeanFieldSort
 * @Description:
 * @Date: 2020/9/11 22:18
 * *
 * @author: achao<achao1441470436 @ gmail.com>
 * @version: 1.0
 * @since: JDK 1.8
 */
@Repeatable(BeanFieldSort.BeanFieldSorts.class)
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BeanFieldSort {
    /**
     * 序号
     *
     * @return
     */
    int order();
    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    @interface BeanFieldSorts {
        BeanFieldSort[] value();
    }
}

这样就可以重复注解了

如果我们需要取出注解里面的order

使用之前的方式就会报空指针了,运行结果也打印出来为true

Field field = UserInfo.class.getDeclaredField("serialVersionUID");
    BeanFieldSort empty = field.getAnnotation(BeanFieldSort.class);
        System.out.println("---");
        System.out.println(Objects.isNull(empty));
//        empty.order();        NPE

正确方式是使用

Field field = UserInfo.class.getDeclaredField("serialVersionUID");
BeanFieldSort.BeanFieldSorts annotation = field.getAnnotation(BeanFieldSort.BeanFieldSorts.class);
for (BeanFieldSort beanFieldSort : annotation.value()) {
    System.out.println(beanFieldSort.order());
}

即可

相关文章
|
安全 算法 Go
有向图的强联通分量(SCC)Tarjan算法
有向图的强联通分量(SCC)Tarjan算法
1009 0
|
负载均衡 前端开发 应用服务中间件
|
机器学习/深度学习 数据采集 编解码
6万字解决算法面试中的深度学习基础问题(一)
6万字解决算法面试中的深度学习基础问题(一)
592 0
6万字解决算法面试中的深度学习基础问题(一)
|
数据安全/隐私保护 容器 .NET
再谈web.config/app.config敏感数据加/解密的二种方法
转载请注明来自"菩提树下的杨过"-http://www.cnblogs.com/yjmyzz/archive/2008/08/22/1274395.html   一.利用代码加解密   using System.
1470 0
|
2天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8072 2
|
11天前
|
域名解析 人工智能 Linux
|
21天前
|
Linux Go 开发工具
手机上跑 DeepSeek 智能体:开源安卓客户端 DSH Go 安装与使用指南
DSH Go 是一款开源安卓客户端,将 DeepSeek Harness 智能体引擎装进手机:免 Root、免 Termux,一键安装即用;支持本机运行(内置 Ubuntu+Node.js)或远程接管电脑会话;具备插话打断、过程折叠、屏幕操控、端到端加密分享等特色功能,真正实现智能体“口袋化”。
18727 64
|
19天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
10118 13
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
5天前
|
人工智能 安全 网络安全