项目里做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)); } }