注释不是从接口方法继承的

vit*_*aly 10 java annotations

我有一个带注释方法的接口.注释标有@Inherited,所以我希望实现者继承它.但事实并非如此:

码:

import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
import java.util.Arrays;

public class Example {

    public static void main(String[] args) throws SecurityException, NoSuchMethodException {
        TestInterface obj = new TestInterface() {
            @Override
            public void m() {}
        };

        printMethodAnnotations(TestInterface.class.getMethod("m"));
        printMethodAnnotations(obj.getClass().getMethod("m"));
    }

    private static void printMethodAnnotations(Method m) {
        System.out.println(m + ": " + Arrays.toString(m.getAnnotations()));
    }
}

interface TestInterface {
    @TestAnnotation
    public void m();
}

@Retention(RetentionPolicy.RUNTIME)
@Inherited
@interface TestAnnotation {}
Run Code Online (Sandbox Code Playgroud)

上面的代码打印:

public abstract void annotations.TestInterface.m():[@ annotations.TestAnnotation()]

public void annotations.Example $ 1.m():[]

所以,问题是为什么不obj.m()@TestAnnotation,尽管它实现了标有一个方法@TestAnnotation@Inherited

Abh*_*kar 25

的javadocjava.lang.annotation.Inherited:

请注意,如果使用带注释的类型来注释除类之外的任何内容,则此元注释类型不起作用.另请注意,此元注释仅导致注释从超类继承; 已实现接口上的注释无效.

  • Woa,同时回答=) (2认同)

Gil*_*zan 18

来自@Inherited javadoc:

请注意,如果使用带注释的类型来注释除类之外的任何内容,则此元注释类型不起作用.另请注意,此元注释仅导致注释从超类继承; 已实现接口上的注释无效

总之,它不适用于方法.