前言注解想必大家都用过,也叫元数据,是一种代码级注解,可以标记和描述类或方法等元素,如Spring框架中的@Service、@Component。那么今天想问大家的是,类是继承的,注解可以继承吗?它可能与您的想法不同。如果您有兴趣,可以在下面阅读。简单的注解继承demo下面来验证一下注解的继承性。自定义注解@Target({ElementType.METHOD,ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)public@interfaceTestAnnotation{Stringvalue();}可以使用自定义注解@TestAnnotation(value="Class")staticclassParent{@TestAnnotation(value="Method")publicvoidmethod(){}}staticclassChildextendsParent{@Overridepublicvoidmethod(){}}父类和注解里面的方法用过的。Child类继承Parent类,重写父类的方法来验证注解是否存在。publicstaticvoidmain(String[]args)throwsNoSuchMethodException{Parentparent=newParent();log.info("ParentClass:{}",getAnnoValue(parent.getClass().getAnnotation(TestAnnotation.class)));log.info("ParentMethod:{}",getAnnoValue(parent.getClass().getMethod("method").getAnnotation(TestAnnotation.class)));孩子孩子=新孩子();log.info("ChildClass:{}",getAnnoValue(child.getClass().getAnnotation(TestAnnotation.class)));log.info("ChildMethod:{}",getAnnoValue(child.getClass().getMethod("方法").getAnnotation(TestAnnotation.class)));}privatestaticStringgetAnnoValue(TestAnnotationannotation){if(annotation==null){return"Annotationnotfound";}返回注解值();}输出结果如下:可以看到父类的类和方法上的注解可以正确获取,但是子类的类和方法不能。这说明默认情况下,子类和子类的方法,父类的注解和父类的方法是不能自动继承的。使用@Inherited演示查了网上资料后,在注解上标记@Inherited元注解,实现注解的继承。那么,是否可以通过将@TestAnnotation注解标记为@Inherited来一键解决问题呢?重新运行,结果如下:可以看到子类可以获取到父类上的注解;虽然子类的方法重写了父类的方法,注解本身也支持继承,但是还是获取不到方法上的注解。如何覆盖方法继承注解?实际上,@Inherited只能实现对类的注解继承。要实现方法注解的继承,可以通过反射在继承链上找到方法注解。听起来是不是很麻烦?好在Spring框架中提供了AnnotatedElementUtils类,方便我们处理注解的继承。调用AnnotatedElementUtils的findMergedAnnotation()方法可以帮助我们找到父类和接口、父类方法和接口方法上的注解,实现一键查找继承链的注解:输出结果如图下图:总结可以通过标签元素传递自定义注解注解@Inherited实现了注解的继承,但这只适用于类。如果要继承定义在接口或方法上的注解,可以使用Spring的工具类AnnotatedElementUtils。
