场景:
在自定义注解中,估计大家都知道三大必备元注解,分别为:@Target、@Retention、@Inherited,前两者不再赘述解释,主要是 @Inherited 可能还有人不太明白,一起看下
一、@Inherited 顾名思义,可被继承的注解
1、分别定义注解 ATable、BTable,如下:
package com.hkl.mpjoin.modules.testAnnotations.annotations;import java.lang.annotation.*;/*** Description:A注解标识
* Author:hkl
* Date:2022/12/2
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface ATable {String name() default "";
}
package com.hkl.mpjoin.modules.testAnnotations.annotations;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** Description:B注解标识
* Author:hkl
* Date:2022/12/2
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface BTable {String name() default "";
}
2、分别定义 DTO 测试用
TestAnnotationDtoOne
package com.hkl.mpjoin.modules.testAnnotations;import com.hkl.mpjoin.modules.testAnnotations.annotations.ATable;/*** Description:测试注解dto类1
* Author:hkl
* Date:2022/12/2
*/
@ATable
public class TestAnnotationDtoOne {public String testOneStr = "TestAnnotationDtoOne";}
TestAnnotationDtoTwo
package com.hkl.mpjoin.modules.testAnnotations;import com.hkl.mpjoin.modules.testAnnotations.annotations.BTable;/*** Description:测试注解dto类2
* Author:hkl
* Date:2022/12/2
*/
@BTable
public class TestAnnotationDtoTwo extends TestAnnotationDtoOne {public String testTwoStr = "TestAnnotationDtoTwo";}
TestAnnotationDtoTwo 继承 TestAnnotationDtoOne
二、获取注解验证
1、父类注解标记 @Inherited 的情况
//验证 @Inherited 元注解 startClass testAnnotationDtoTwoClass = TestAnnotationDtoTwo.class;Annotation[] annotations = testAnnotationDtoTwoClass.getAnnotations();System.out.println("annotations = " + Arrays.asList(annotations));//验证 @Inherited 元注解 end
输出:
annotations = [@com.hkl.mpjoin.modules.testAnnotations.annotations.ATable(name=""), @com.hkl.mpjoin.modules.testAnnotations.annotations.BTable(name="")]
可以获取到 ATable、BTable 两个注解
2、父类注解没有标记 @Inherited 的情况
//验证 @Inherited 元注解 startClass testAnnotationDtoTwoClass = TestAnnotationDtoTwo.class;Annotation[] annotations = testAnnotationDtoTwoClass.getAnnotations();System.out.println("annotations = " + Arrays.asList(annotations));//验证 @Inherited 元注解 end
输出:
annotations = [@com.hkl.mpjoin.modules.testAnnotations.annotations.BTable(name="")]
只可以获取到 BTable 注解
三、总结
1、@Inherited 元注解的作用是标记自定义注解是否可以被继承
2、被 @Inherited 标记的自定义注解,可以被自定义注解标记的类的子类 class 获取到
下一篇:Linux下时间相关接口