gpt4 book ai didi

java - 注解不是继承自接口(interface)方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:02:53 24 4
gpt4 key购买 nike

我有一个带有注释方法的接口(interface)。注释用 @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 {}

上面的代码打印:

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

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

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

最佳答案

来自javadocs java.lang.annotation.Inherited:

Note that this meta-annotation type has no effect if the annotated type is used to annotate anything other than a class. Note also that this meta-annotation only causes annotations to be inherited from superclasses; annotations on implemented interfaces have no effect.

关于java - 注解不是继承自接口(interface)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12428858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com