Java8中引入的一个新注解@Repeatable
,该注解只能标记在其他注解上,表示被标记的注解可以重复声明在类、属性、方法等上面;但@Repeatable
注解还是得需要定义容器注解配合才能使用,所以也只是增强了代码的可读性;
| public class AnnotationTest { |
| |
| |
| |
| |
| |
| @Roles({@Role("System"), @Role("Business")}) |
| private User zs; |
| } |
| |
| |
| |
| |
| @Documented |
| @Retention(RetentionPolicy.RUNTIME) |
| @Target({ElementType.FIELD}) |
| @interface Role { |
| String value(); |
| } |
| |
| |
| |
| |
| @Documented |
| @Retention(RetentionPolicy.RUNTIME) |
| @Target({ElementType.FIELD}) |
| @interface Roles { |
| Role[] value(); |
| } |
| |
| class User { |
| private String name; |
| } |
| |
| public class AnnotationTest { |
| |
| |
| |
| |
| |
| @Role("System") |
| @Role("Business") |
| private User zs; |
| } |
| |
| |
| |
| |
| @Documented |
| @Retention(RetentionPolicy.RUNTIME) |
| @Target({ElementType.FIELD}) |
| |
| @Repeatable(Roles.class) |
| @interface Role { |
| String value(); |
| } |
| |
| |
| |
| |
| @Documented |
| @Retention(RetentionPolicy.RUNTIME) |
| @Target({ElementType.FIELD}) |
| @interface Roles { |
| Role[] value(); |
| } |
| |
| class User { |
| private String name; |
| } |
| |
2. 获取重复声明注解的值
| public class AnnotationTest { |
| |
| @Role("System") |
| @Role("Business") |
| private User zs; |
| |
| public static void main(String[] args) throws Exception { |
| Field zs = AnnotationTest.class.getDeclaredField("zs"); |
| |
| Roles roles = zs.getAnnotation(Roles.class); |
| Role[] roleArr = roles.value(); |
| for (Role role : roleArr) { |
| System.out.println(role.value()); |
| } |
| } |
| } |
| |
| @Documented |
| @Retention(RetentionPolicy.RUNTIME) |
| @Target({ElementType.FIELD}) |
| @Repeatable(Roles.class) |
| @interface Role { |
| String value(); |
| } |
| |
| @Documented |
| @Retention(RetentionPolicy.RUNTIME) |
| @Target({ElementType.FIELD}) |
| @interface Roles { |
| Role[] value(); |
| } |
| |
| class User { |
| private String name; |
| } |
| |
3. 类型注解介绍
在自定义一个注解的时候可以使用@Target元注解标记在自定义的注解上面,表示该自定义注解所修饰的对象范围,其@Target元注解的值是一个ElementType
枚举类型的数组,在Java8中ElementType
枚举新增了TYPE_PARAMETER
和TYPE_USE
两个实例,可配合Checker Framework
做编译期检查;其所有元素介绍如下:
- TYPE:表示注解可标记在类、接口(包括注解类型)、枚举上
- FIELE:表示注解可标记在成员变量、枚举实例上
- METHOD:表示注解可标记在方法上
- PARAMETER:表示注解可标记在参数上
- CONSTRUCTOR:表示注解可标记在构造方法上
- LOCAL_VARIABLE:表示注解可标记在局部变量上
- ANNOTATION_TYPE:表示注解可标记在注解类型上
- PACKAGE:表示注解可标记在包上
- TYPE_PARAMETER:表示注解可标记在类型变量声明语句中
- TYPE_USE:表示注解可标记在类型变量使用语句中
原文链接:https://blog.csdn.net/gu19930914/article/details/115752472
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)