注解不是从接口方法继承的 [英] Annotation is not inherited from interface method

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

问题描述

我有一个带有注释方法的接口.注释用 @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 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?

推荐答案

来自 javadocs:

From the javadocs of java.lang.annotation.Inherited:

注意这个元注解类型在注解的时候没有效果type 用于注释除类以外的任何内容.还要注意的是这个元注释只会导致注释被继承超类;已实现接口上的注解无效.

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天全站免登陆