@Inherited 原注解功能介绍
@Inherited 底层
package java.lang.annotation;
/**
* Indicates that an annotation type is automatically inherited. If
* an Inherited meta-annotation is present on an annotation type
* declaration, and the user queries the annotation type on a class
* declaration, and the class declaration has no annotation for this type,
* then the class's superclass will automatically be queried for the
* annotation type. This process will be repeated until an annotation for this
* type is found, or the top of the class hierarchy (Object)
* is reached. If no superclass has an annotation for this type, then
* the query will indicate that the class in question has no such annotation.
*
* <p>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.
*
* @author Joshua Bloch
* @since 1.5
* @jls 9.6.3.3 @Inherited
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
}
举例说明
代码
public class Inheritedtext {
public static void main(String[] args) {
//此时的 A.isAnnotationPresent(aa.class);
//意思就是:注释aa是否在此A上。如果在则返回true;不在则返回false。
System.out.println(A.class.isAnnotationPresent(aa.class));
System.out.println(B.class.isAnnotationPresent(aa.class));
System.out.println(C.class.isAnnotationPresent(aa.class));
System.out.println(D.class.isAnnotationPresent(aa.class));
}
}
//定义注解aa
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@interface aa{}
//被aa注解的类
@aa
class A{
}
class B extends A{
}
//未被aa注解的类
class C {
}
class D extends C{
}
结果
true
true
false
false
效果图


作用
如果一个类用上了@Inherited修饰的注解,那么其子类也会继承这个注解
注意
- 接口用上个@Inherited修饰的注解,其实现类不会继承这个注解
- 父类的方法用了@Inherited修饰的注解,子类也不会继承这个注解

浙公网安备 33010602011771号