我有一个定义如下的注释:
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Retriable {
}
我正在使用它:
@Retriable
interface MyInterface {
public void myMethod();
}
现在,我有第二个接口,它扩展了第一个接口:
interface MySecondInterface extends MyInterface {
}
我想为MySecondInterface
获取 所有 注释,这意味着我还希望获得在超级接口上定义的注释。 / p>
我尝试了什么:
Class clazz = MySecondInterface.class;
Retriable annotation = clazz.getAnnotation(Retriable.class);
System.out.println("Retriable annotation: " + annotation);
Annotation[] annotations = clazz.getAnnotations();
System.out.println("Annotations: " + Arrays.toString(annotations));
annotations = clazz.getDeclaredAnnotations();
System.out.println("Declared Annotations: " + Arrays.toString(annotations));
结果是:
Retriable annotation: null
Annotations: []
Declared Annotations: []
在所有情况下,它都找不到从Retriable
继承的MyInterface
注释。 (DEMO)
有没有办法让它识别超级界面的注释?
答案 0 :(得分:0)
来自java.lang.annotation.Inherited
的javadoc:
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.
所以改变接口到类。它会影响
@Retriable
class MyClass {
public void myMethod(){
}
}
class MySecondClass extends MyClass {
}