注释不能从接口方法继承 [英] Annotation is not inherited from interface method

查看:281
本文介绍了注释不能从接口方法继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有带注解的方法的接口。注释标有 @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:

code:

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 {}

以上code打印:

The above code prints:

公共抽象无效annotations.TestInterface.m():@ annotations.TestAnnotation()]

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

公共无效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?

推荐答案

从的 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.

这篇关于注释不能从接口方法继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆