直接代码说话,说明信息详见注释。。
首先是自定义的使用@Inherited标注的注解----InheritedTest.java
package com.jadyer.annotation.inherited; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface InheritedTest { String value(); } //默认的父类中的Annotation并不会被继承至子类中,若想让子类也继承父类中的Annotation的话 //可以在定义Annotation型态时加上java.lang.annotation.Inherited型态的Annotation
然后是使用我们自定义的@InheritedTest注解标注的父类----Parent.java
package com.jadyer.annotation.inherited; @InheritedTest("Jadyer") public class Parent { @InheritedTest("JavaEE") public void doSomething() { System.out.println("Parent do something"); } }
接着是继承了Parent.java的子类----Child.java
package com.jadyer.annotation.inherited; public class Child extends Parent { @Override public void doSomething() { System.out.println("Child do something"); } }
最后通过反射机制测试子类是否继承了父类中的@InheritedTest注解----Test.java
package com.jadyer.annotation.inherited; import java.lang.reflect.Method; /** * 通过反射的方式测试Child类中是否继承了Parent中的InheritedTest注解 */ public class Test { public static void main(String[] args) throws SecurityException, NoSuchMethodException { classTest(); methodTest(); } /** * 通过反射方式测试子类是否会继承父类中定义在类上面的注解 */ public static void classTest(){ Class<Child> c = Child.class; if (c.isAnnotationPresent(InheritedTest.class)) { InheritedTest inheritedTest = c.getAnnotation(InheritedTest.class); String value = inheritedTest.value(); System.out.println(value); } } /** * 通过反射方式测试子类是否会继承父类中定义在方法上面的注解 */ public static void methodTest() throws SecurityException, NoSuchMethodException{ Class<Child> c = Child.class; Method method = c.getMethod("doSomething", new Class[]{}); if (method.isAnnotationPresent(InheritedTest.class)) { InheritedTest inheritedTest = method.getAnnotation(InheritedTest.class); String value = inheritedTest.value(); System.out.println(value); } } } /**********【运行输出】*********************************************************************/ //通过运行输出,我们会发现,结果只输出了Jadyer,而没有JavaEE //若注释掉Child.java中的doSomething(),再运行,结果输出了Jadyer和JavaEE //这是为什么呢?问题就出在Child.java重写了Parent.java的doSomething()方法 /**********【当父类中的注解被@Inherited标注的情况下】*******************************************/ //如果父类的注解是定义在类上面,那么子类是可以继承过来的 //如果父类的注解定义在方法上面,那么子类仍然可以继承过来 //如果子类重写了父类中定义了注解的方法,那么子类将无法继承该方法的注解 //即子类在重写父类中被@Inherited标注的方法时,会将该方法连带它上面的注解一并覆盖掉 //【注意】JDK文档中对此种情况的叙述并不全面 //〖另外〗接口的实现类是无法继承接口中所定义的被@Inherited标注的注解的 /*****************************************************************************************/