Java中的@Repeatable注解的作用详解
1. 前言
最近无意看到某些注解上有@Repeatable,出于比较好奇,因此稍微研究并写下此文章。
@Repeatable注解是用来标注一个注解在同一个地方可重复使用的一个注解,比如说你定义了一个注解,如果你的注解没有标记@Repeatable这个JDK自带的注解,那么你这个注解在引用的地方就只能使用一次。
2. 先说结论
@Repeatable的作用:使被他注释的注解可以在同一个地方重复使用。
具体使用如下:
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Repeatable(value = MyAnnotationList.class) public @interface MyAnnotation { String name(); } @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotationList { // 被 @Repeatable引用的注解中,必须得有被 @Repeatable注释的注解(@MyAnnotation)返回类型的value方法 MyAnnotation[] value(); } public class MyAnnotationTest { @MyAnnotation(name = "Test1") @MyAnnotation(name = "Test2") private void testMethod() { } @MyAnnotationList(value = {@MyAnnotation(name = "Test1"), @MyAnnotation(name = "Test2")}) private void testMethod2() { } }
3. 案例演示
先定义新注解
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { String name(); }
创建新类并使用自定义注解
public class MyAnnotationTest { @MyAnnotation(name = "Test1") private void testMethod(){ } }
当注解@MyAnnotation还没被@Repeatable注释的时候,在testMethod()方法上使用多次,会出现下面报错:
将会提示:@MyAnnotation没被@Repeatable注解,无法重复使用@MyAnnotation
因此在@MyAnnotation上使用@MyAnnotation,如下:
4. 注意事项
@Repeatable(value = MyAnnotationList.class) 中引用了 @MyAnnotationList注解,用于@MyAnnotation注解上,有如下几个细节:
细节一:在引用注解上的@MyAnnotationList的方法中得有value()方法,如下:
细节二:在引用注解上的@MyAnnotationList的方法中得有【被@Repeatable注解的@MyAnnotation注解类型的数组返回值的value方法】
细节三:该案例中,若在方法上重复使用@MyAnnotation注解,实际上也会在运行的时候被包装成MyAnnotationList[] 里面,如下:
细节四:@MyAnnotation可多次使用,但不可多次与@MyAnnotationList一起使用,如下:
细节五:@MyAnnotation可多次使用,但仅可一个与@MyAnnotationList一起使用,但唯一的@MyAnnotation在运行的时候被包装成MyAnnotationList[] 里面,如下:
到此这篇关于Java中的@Repeatable注解的作用详解的文章就介绍到这了,更多相关@Repeatable注解内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
springboot 自定义异常并捕获异常返给前端的实现代码
在开发中,如果用try catch的方式,每个方法都需要单独实现,为了方便分类异常,返回给前端,采用了@ControllerAdvice注解和继承了RuntimeException的方式来实现,具体实现内容跟随小编一起看看吧2021-11-11Spring Boot集成LiteFlow规则引擎的详细过程
本文详细介绍了如何在Spring Boot应用程序中集成LiteFlow规则引擎,并探讨如何使用LiteFlow库来实现业务流程的规则处理,将通过具体的示例来展示如何在Spring Boot应用程序中配置和使用LiteFlow规则引擎,以提高系统的灵活性和可维护性,感兴趣的朋友跟随小编一起看看吧2024-07-07如何在SpringBoot项目中使用Oracle11g数据库
这篇文章主要介绍了在SpringBoot项目中使用Oracle11g数据库的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-06-06
最新评论