java注解学习---@Inherited注解的理解学习(四)

本文通过定义带有@Inherited注解的父类注解和未带此注解的子类注解,演示了如何在Java中实现子类继承父类注解的功能。通过具体代码示例和运行结果分析,帮助读者理解@Inherited注解的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java注解学习---@Inherited注解的理解学习(四)

一、 @Inherited 注解的作用
1、 允许子类继承父类的注解。 (子类中可以获取并使用父类注解)

二、使用代码实现思路
1、定义父类注解: @ParentAnnotation 使用 @Inherited 注解标记。
2、定义子类注解: @ChildAnnotation 不使用@Inherited 注解标记。
3、定义一个普通 Parent 类, 使用 @ParentAnnotation 注解标记
4、定义一个普通 Child 类,继承 Parent 类 , 使用 @ChildAnnotation 注解标记
5、定义一个测试类,根据测试结果,理解 @Inherited 注解。

三、代码实现
1、 定义 @ParentAnnotation 注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value=ElementType.TYPE)
@Inherited
public @interface ParentAnnotation {

}

2、定义 @ChildAnnotation 注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value=ElementType.TYPE)
public @interface ChildAnnotation {

}



3、 定义 Parent 类
@ParentAnnotation
public class Parent {
	
}

4、定义 Child 类
        
@ChildAnnotation
public class Child extends Parent {
	
}

5、测试类
public static void main(String[] args) {
	ParentAnnotation parent = Parent.class.getAnnotation(ParentAnnotation.class);
	ChildAnnotation parentChild = Parent.class.getAnnotation(ChildAnnotation.class);
	System.out.println("parent: "+parent +"   parentChild :"+parentChild);
	System.out.println(" ===== child test ==== ");
	ParentAnnotation childParent = Child.class.getAnnotation(ParentAnnotation.class);
	ChildAnnotation child = Child.class.getAnnotation(ChildAnnotation.class);
	System.out.println("childParent: "+childParent +"   child :"+child);
}

6、 程序运行结果:
parent: @com.haha.study.annotation.inherited.simple.ParentAnnotation()   parentChild :null
 ===== child test ==== 
childParent: @com.haha.study.annotation.inherited.simple.ParentAnnotation()   child :@com.haha.study.annotation.inherited.simple.ChildAnnotation()

7、结果分析: 可以看到 childParent 的结果不是 null , 说明了 Child 类继承了 Parent 类,也继承了 Parent 类的标记注解 @ParentAnnotation 。 反之去掉 @ParentAnnotation 注解上的 @Inherited 注解, 再进行测试 , childParent 的结果变成了 null 。


四、 总结
1、 @Inherited 注解的作用: 允许子类继承父类的注解。 即在两个类之间存在继承关系,且父类标记的注解使用了 @Inherited 注解(注: 总感觉这里表述不清,参考 @ParentAnnotation 注解的定义即可),这时继承的子类可以使用父类的注解。

2、@Inherited 注解的误解: 子注解类继承父注解类 --- @ChildAnnotation 注解类 继承@ParentAnnotation 注解类。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值