Java方法注释如何与方法重写一起使用?

Tra*_*ebb 63 java inheritance overriding annotations

我有一个父类Parent和一个子类Child,由此定义:

class Parent {
    @MyAnnotation("hello")
    void foo() {
        // implementation irrelevant
    }
}
class Child {
    @Override
    foo() {
        // implementation irrelevant
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我获得Method参考Child::foo,childFoo.getAnnotation(MyAnnotation.class)会给我@MyAnnotation吗?还是会的null

我更感兴趣的是注释如何或是否与Java继承一起使用.

tru*_*ity 76

http://www.eclipse.org/aspectj/doc/released/adk15notebook/annotations.html#annotation-inheritance逐字复制:

注释继承

理解与注释继承相关的规则很重要,因为它们基于注释的存在与否而对连接点匹配产生影响.

默认情况下,不会继承注释.鉴于以下计划

        @MyAnnotation
        class Super {
          @Oneway public void foo() {}
        }

        class Sub extends Super {
          public void foo() {}
        }
Run Code Online (Sandbox Code Playgroud)

然后Sub没有MyAnnotation注释,并且Sub.foo()不是一个@Oneway方法,尽管它覆盖了Super.foo()哪个是.

如果注释类型具有元注释,@Inherited则类上的该类型的注释将导致注释被子类继承.因此,在上面的示例中,如果MyAnnotation类型具有@Inherited属性,那么Sub将具有MyAnnotation注释.

@Inherited当用于注释除类型之外的任何内容时,注释不会被继承.实现一个或多个接口的类型永远不会从它实现的接口继承任何注释.

  • 另外,在我问之前,我已经搜索过了真相,我找到了这个页面.恭喜,您现在是这些搜索结果的一部分.这就是为什么这个网站在这里.:)此外,您的答案比查看该文档更简洁. (35认同)

Sai*_*ali 11

您已经找到了答案:JDK中没有提供方法注释继承.

但是,攀登超类链以寻找带注释的方法也很容易实现:

/**
 * Climbs the super-class chain to find the first method with the given signature which is
 * annotated with the given annotation.
 *
 * @return A method of the requested signature, applicable to all instances of the given
 *         class, and annotated with the required annotation
 * @throws NoSuchMethodException If no method was found that matches this description
 */
public Method getAnnotatedMethod(Class<? extends Annotation> annotation,
                                 Class c, String methodName, Class... parameterTypes)
        throws NoSuchMethodException {

    Method method = c.getMethod(methodName, parameterTypes);
    if (method.isAnnotationPresent(annotation)) {
        return method;
    }

    return getAnnotatedMethod(annotation, c.getSuperclass(), methodName, parameterTypes);
}
Run Code Online (Sandbox Code Playgroud)


jre*_*rey 7

使用Spring Core可以解决问题

AnnotationUtils.java