Java中@Inherited注解的运用
我们自定义注解(Annotation)时,把自定义的注解标注在父类上不会被子类所继承,但是我们可以在定义注解时给我们自定义的注解标注一个@Inherited注解来实现注解继承。
自定义的注解代码如下:
package com.xdf.annotation;import java.lang.annotation.Inherited;import java.lang.annotation.Retention;@Inherited@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)public @interface InheritedAnnotation {String value();}package com.xdf.annotation;public abstract class AbstractParent {@InheritedAnnotation(value = "parent abstractMethod ") public abstract void abstractMethod();@InheritedAnnotation(value = "Parent's doExtends") public void doExtends() { System.out.println(" AbstractParent doExtends ..."); }}package com.xdf.annotation;public class SubClassImpl extends AbstractParent{@Overridepublic void abstractMethod() {System.out.println("子类实现抽象父类的抽象方法");}}package com.xdf.annotation;import java.lang.reflect.Method;public class InheritedAnnotationTest {public static void main(String[] args) throws SecurityException, NoSuchMethodException { Class<SubClassImpl> clazz=SubClassImpl.class; //abstractMethod Method method = clazz.getMethod("abstractMethod", new Class[]{}); if(method.isAnnotationPresent(InheritedAnnotation.class)){ InheritedAnnotation ma = method.getAnnotation(InheritedAnnotation.class); System.out.println("子类实现的抽象方法继承到父类抽象方法中的Annotation,其信息如下:"); System.out.println(ma.value()); }else{ System.out.println("子类实现的抽象方法没有继承到父类抽象方法中的Annotation"); } Method methodOverride = clazz.getMethod("doExtends", new Class[]{}); if(methodOverride.isAnnotationPresent(InheritedAnnotation.class)){ InheritedAnnotation ma = methodOverride.getAnnotation(InheritedAnnotation.class); System.out.println("子类doExtends方法继承到父类doExtends方法中的Annotation,其信息如下:"); System.out.println(ma.value()); }else{ System.out.println("子类doExtends方法没有继承到父类doExtends方法中的Annotation"); }} }子类实现的抽象方法没有继承到父类抽象方法中的Annotation子类doExtends方法继承到父类doExtends方法中的Annotation,其信息如下:Parent's doExtends
package com.xdf.annotation;@InheritedAnnotation(value="parent") //把自定义注解标注在父类上public abstract class AbstractParent {@InheritedAnnotation(value = "parent abstractMethod ") public abstract void abstractMethod();@InheritedAnnotation(value = "Parent's doExtends") public void doExtends() { System.out.println(" AbstractParent doExtends ..."); }}if(clazz.isAnnotationPresent(InheritedAnnotation.class)){ InheritedAnnotation cla = clazz.getAnnotation(InheritedAnnotation.class); System.out.println("子类继承到父类类上Annotation,其信息如下:"); System.out.println(cla.value()); }else{ System.out.println("子类没有继承到父类类上Annotation"); }子类实现的抽象方法没有继承到父类抽象方法中的Annotation子类doExtends方法继承到父类doExtends方法中的Annotation,其信息如下:Parent's doExtends子类没有继承到父类类上Annotation
子类实现的抽象方法没有继承到父类抽象方法中的Annotation子类doExtends方法继承到父类doExtends方法中的Annotation,其信息如下:Parent's doExtends子类继承到父类类上Annotation,其信息如下:parent