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

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 注解类。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章