@Inherited:指定子类可以继承父类的注解,只能是类上的注解,方法和字段的注解不能继承。即如果父类上的注解是@Inherited修饰的就能被子类继承。
package com.fyd.java.annotation;
import java.lang.annotation.*;
public class Test {
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
// @Inherited
static @interface W{
}
@W
static class A{
}
static class B extends A{
}
public static void main(String[] args) {
//return inherited annotation
System.out.println(B.class.getAnnotation(W.class));
System.out.println(B.class.getDeclaredAnnotation(W.class));
}
}
输出:
null
null
package com.fyd.java.annotation;
import java.lang.annotation.*;
public class Test {
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
static @interface W{
}
@W
static class A{
}
static class B extends A{
}
public static void main(String[] args) {
//return inherited annotation
System.out.println(B.class.getAnnotation(W.class));
System.out.println(B.class.getDeclaredAnnotation(W.class));
}
}
输出
@com.fyd.java.annotation.Test$W()
null
注:
getAnnotation(Class<T> annotationClass): 返回改程序元素上存在的、指定类型的注解,如果该类型注解不存在,则返回null。
getDeclaredAnnotations(Class<T> annotationClass):返回直接存在于此元素上的所有注释。与此接口中的其他方法不同,该方法将忽略继承的注释。(如果没有注释直接存在于此元素上,则返回长度为零的一个数组。)该方法的调用者可以随意修改返回的数组;这不会对其他调用者返回的数组产生任何影响。