@Inherited:原註解,用於修飾自訂註解的metadata
使用此註解修飾自訂註解時,效果是可以讓自訂註解有繼承特性,當將帶有@Inherited的註解使用在A類名上(B的父類),則subClass B類自動繼承該註解。
註:將帶有@Inherited的註解使用在類的方法,屬性則是無效的。即使用在父類的方法和屬性上,子類不會繼承該註解。大家可能暈了,這裡說的繼承是superClass-A 類或者方法上帶有註解,subClass-B上不帶註解,這時當B extends A 時,能不能在B上自動帶上這個帶有@Inherited的註解。
public class AnotationTest { public static void main(String[] args) throws NoSuchMethodException, SecurityException, NoSuchFieldException { //子類class Class<Child> clazz = Child.class; //對類上的註解進行驗證進行測試 if (clazz.isAnnotationPresent(InheritedTest.class)) { System.out.println(clazz.getAnnotation(InheritedTest.class).value()); } if (clazz.isAnnotationPresent(NoInheritedTest.class)) { System.out.println(clazz.getAnnotation(NoInheritedTest.class).value()); } //對子類需要覆蓋的方法 進行測試 Method method = clazz.getMethod("methodNeedOverrid", null); if (method.isAnnotationPresent(InheritedTest.class)) { System.out.println(method.getAnnotation(InheritedTest.class).value()); } if (method.isAnnotationPresent(NoInheritedTest.class)) { System.out.println(method.getAnnotation(NoInheritedTest.class).value()); } //對子類不需要覆蓋的方法 進行測試,說白了此方法是父類的,肯定有註解,不管是帶與不帶@Inherited Method method2 = clazz.getMethod("methodNotNeedOverrid", null); if (method2.isAnnotationPresent(InheritedTest.class)) { System.out.println(method2.getAnnotation(InheritedTest.class).value()); } if (method2.isAnnotationPresent(NoInheritedTest.class)) { System.out.println(method2.getAnnotation(NoInheritedTest.class).value()); } //對繼承的屬性測試,屬性也是父類的也肯定帶 Field field = clazz.getField("fieldString"); if (field.isAnnotationPresent(InheritedTest.class)) { System.out.println(field.getAnnotation(InheritedTest.class).value()); } if (field.isAnnotationPresent(NoInheritedTest.class)) { System.out.println(field.getAnnotation(NoInheritedTest.class).value()); } }}// 無任何註解,如果在主程度中我們檢測到Child中出現了註解,則說明父類的註解繼承到子類了class Child extends Parent { public String fieldString; @Override public void methodNeedOverrid() { }}@InheritedTest("使用Inherited的註解類")@NoInheritedTest("未使用Inherited的註解類")class Parent { @InheritedTest("方法-子類需要覆蓋且使用Inherited的註解") @NoInheritedTest("方法-子類需要覆蓋且未使用Inherited的註解") public void methodNeedOverrid() { } @InheritedTest("方法-子類不需要覆蓋且使用Inherited的註解") @NoInheritedTest("方法-子類不需要覆蓋且未使用Inherited的註解") public void methodNotNeedOverrid() { } @InheritedTest("屬性-在父類屬性上使用Inherited的註解") @NoInheritedTest("屬性-在父類屬性上未使用Inherited的註解") public String fieldString;}
@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})@Inheritedpublic @interface InheritedTest { String value() default "lei";}
@Retention(RetentionPolicy.RUNTIME)public @interface NoInheritedTest { String value() default "no inheritated";}