我有一个带注释方法的接口.注释标有@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?
Gil*_*zan 18
来自@Inherited javadoc:
请注意,如果使用带注释的类型来注释除类之外的任何内容,则此元注释类型不起作用.另请注意,此元注释仅导致注释从超类继承; 已实现接口上的注释无效
总之,它不适用于方法.
| 归档时间: |
|
| 查看次数: |
8486 次 |
| 最近记录: |