问题描述
我有一个带有注释方法的接口.注释用 @Inherited
标记,所以我希望实现者继承它.然而,事实并非如此:
I have an interface with an annotated method. The annotation is marked with @Inherited
, so I expect an implementor to inherit it. However, it is not the case:
代码:
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 {}
上面的代码打印:
public abstract void annotations.TestInterface.m(): [@annotations.TestAnnotation()]
public void annotations.Example$1.m(): []
public void annotations.Example$1.m(): []
所以问题是为什么 obj.m()
没有 @TestAnnotation
尽管它实现了一个用 @TestAnnotation
标记的方法@Inherited
是什么?
So the question is why does not the obj.m()
have @TestAnnotation
despite that it implements a method marked with @TestAnnotation
which is @Inherited
?
推荐答案
来自 :
From the javadocs of java.lang.annotation.Inherited
:
注意这个元注解类型在注解的时候没有效果type 用于注释除类以外的任何内容.还要注意的是这个元注释只会导致注释被继承超类;已实现接口上的注解无效.
这篇关于注解不是从接口方法继承的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!