@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修饰的注解,子类也不会继承这个注解
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构