項目里做AOP,需要用到注解,要求有些特別,注解需要加到接口方法上,所以不能直接把 Annotation 作為切點的判斷方式,必須通過 Interface 去獲取。一開始嘗試用 @Inherited 讓方法繼承注解,但是失敗,在網上搜到了Java注解的繼承這篇文章,明確了原因:
1、首先要想Annotation能被繼承,需要在注解定義的時候加上@Inherited,並且如果要被反射應用的話,就需要還有個事@Retention(RetentionPolicy.RUNTIME)標識
2、JDK文檔中說明的是:只有在類上應用Annotation才能被繼承,而實際應用結果是:除了類上應用的Annotation能被繼承外,沒有被重寫的方法的Annotation也能被繼承;
3、當方法被重寫后,Annotation不會被繼承
4、Annotation的繼承不能應用在接口上
后續寫了一個簡單的測試類,已經通過
@Inherited @Retention(RetentionPolicy.RUNTIME) public @interface AnnotationWithInherited { String value(); }
public class InheritedTest { @Data public static class Father { String name; @AnnotationWithInherited("father") public String print() { return name; } } @Data public static class Children1 extends Father { String childrenName; } @Data public static class Children2 extends Father { String childrenName; public String print() { return name; } } @Test public void test() throws NoSuchMethodException { Children1 notOverrideMethod = new Children1(); Children2 overrideMethod = new Children2(); Assert.assertNotNull(notOverrideMethod.getClass().getMethod("print").getAnnotation(AnnotationWithInherited.class)); Assert.assertNull(overrideMethod.getClass().getMethod("print").getAnnotation(AnnotationWithInherited.class)); } }