java中的注解可以继承吗对吗(JAVA中的注解可以继承吗?)
前言
注解想必大家都用过 ,也叫元数据 ,是一种代码级别的注释,可以对类或者方法等元素做标记说明 ,比如Spring框架中的@Service ,@Component等 。那么今天我想问大家的是类被继承了 ,注解能否继承呢?可能会和大家想的不一样 ,感兴趣的可以往下看 。
简单注解继承演示
我们不妨来验证下注解的继承。
自定义一个注解 @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface TestAnnotation { String value(); } 注解可以被标记在类或者方法上 使用自定义注解 @TestAnnotation(value = "Class") static class Parent { @TestAnnotation(value = "Method") public void method() { } } static class Child extends Parent { @Override public void method() { } } Parent类和里面的方法使用了注解 Child类继承了Parent类, 重写了父类的方法 验证是否存在注解 public static void main(String[] args) throws NoSuchMethodException { Parent parent = new Parent(); log.info("ParentClass: {}", getAnnoValue(parent.getClass().getAnnotation(TestAnnotation.class))); log.info("ParentMethod: {}", getAnnoValue(parent.getClass().getMethod("method").getAnnotation(TestAnnotation.class))); Child child = new Child(); log.info("ChildClass: {}", getAnnoValue(child.getClass().getAnnotation(TestAnnotation.class))); log.info("ChildMethod: {}", getAnnoValue(child.getClass().getMethod("method").getAnnotation(TestAnnotation.class))); } private static String getAnnoValue(TestAnnotation annotation) { if(annotation == null) { return "未找到注解"; } return annotation.value(); }输出结果如下:
可以看到 ,父类的类和方法上的注解都可以正确获得 ,但是子类的类和方法却不能 。这说明 ,默认情况下 ,子类以及子类的方法 ,无法自动继承父类和父类方法上的注解 。
使用@Inherited演示
查了网上资料以后,在注解上标记@Inherited元注解可以实现注解的继承 。那么 ,把@TestAnnotation注解标记了@Inherited,就可以一键解决问题了吗?
重新运行 ,得到结果如下:
可以看到,子类可以获得父类类上的注解;子类方法虽然是重写父类方法 ,并且注解本身也支持继承 ,但还是无法获得方法上的注解 。
如何重写方法继承注解?
实际上,@Inherited只能实现类上的注解继承 。要想实现方法上注解的继承 ,你可以通过反射在继承链上找到方法上的注解 。是不是听起来很麻烦 ,好在Spring框架中提供了AnnotatedElementUtils类 ,来方便我们处理注解的继承问题 。
调用AnnotatedElementUtils的findMergedAnnotation()方法 ,可以帮助我们找出父类和接口 、父类方法和接口方法上的注解 ,实现一键找到继承链的注解:
输出结果如下图:
总结
自定义注解可以通过标记元注解@Inherited实现注解的继承 ,不过这只适用于类 。如果要继承定义在接口或方法上的注解 ,可以使用Spring的工具类AnnotatedElementUtils 。
如果本文对你有帮助的话 ,请留下一个赞吧
欢迎关注个人公众号——JAVA旭阳
更多学习资料请移步:程序员成神之路创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!