繁体   English   中英

注释继承行为很奇怪

[英]Annotation Inheritance acting weird

下面的代码打印

@MyTestAnnotation():FOO

对于B类和C类,是否将MyTestAnnotation指定为@Inherited。 我认为注释仅在指定@Inherited的情况下才被继承,并且默认注释继承行为是不被继承。 这里发生了什么事?

import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;

public class AnnotationTest {

    public static void main(String[] args) {
        B b = new B();
        C c = new C();
        printMethdodsAndAnotations(b);
        printMethdodsAndAnotations(c);
    }

    public static void printMethdodsAndAnotations(Object obj) {
        Method[] methods = obj.getClass().getMethods();
        for (int i = 0; i < methods.length; i++) {

            Annotation[] annotations = methods[i].getAnnotations();
            if (annotations.length > 0)
            {                               
                for (int j = 0; j < annotations.length; j++) {
                    System.out.println(annotations[j].toString() + ":" + methods[i].getName());
                }
            }
        }
    }
}

//@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyTestAnnotation {

}

abstract class A {
    public abstract void foo();
}

class B extends A {

    @MyTestAnnotation       
    public void foo() {
        System.out.println("B's foo()");
    }
}

class C extends B {

    public void foo2() {
        System.out.println("C's foo()");
    }
}

由于C没有覆盖B#foo() ,所以它继承了它。 它还继承了它附带的所有内容,即。 注释。 如果添加

public void foo() {
    System.out.println("C's foo()");
}

C ,它将没有注释。

您会注意到是否已打印

System.out.println(annotations[j].toString() + ":" + methods[i]); // instead of methods[i].getName()

它打印

@MyTestAnnotation():public void com.sc.B.foo()

该方法是B的方法。 B#foo带有@MyTestAnnotation注释。


另外,@ @Inherited用于类注释。 如javadoc所述

请注意,如果带注释的类型用于注释除类之外的任何内容,则此元注释类型无效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM