注释继承表现得很奇怪

时间:2014-02-06 15:14:42

标签: java annotations

以下代码打印

  

@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()");
    }
}

1 个答案:

答案 0 :(得分:1)

由于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所述

  

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