Inherited元注解

Inherited元注解:普通注解并没有继承功能,@Inherited元注解可以让一个注解具有世袭制(继承),这个注解相对比较简单。

  1. 定义一个生命周期为RUNTIME的普通注解

    package annotation.inherits;
    
    
    import java.lang.annotation.Inherited;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    
    @Retention(RetentionPolicy.RUNTIME)
    
    public @interface CommonAnotation {
    }
    
    
  2. 定义一个生命周期为RUNTIME、具有继承功能的注解。

    package annotation.inherits;
    
    import java.lang.annotation.Inherited;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    
    @Retention(RetentionPolicy.RUNTIME)
    @Inherited
    public @interface InheritAnotation {
    }
    
    
  3. 定义普通father类、son类。father类使用CommonAnotation注解修饰,son类继承父类。

    //Father_Com.java 
    package annotation.inherits;
    
    @CommonAnotation
    public class Father_Com {
    }
    
    
    //Son_Com.java 
    package annotation.inherits;
    public class Son_Com extends Father_Com {
    }
    
    
  4. 定义继承father类、son类。father类使用InheritAnotation注解修饰,son类继承父类。

    
    //Father_In.java
    package annotation.inherits;
    
    @InheritAnotation
    public class Father_In {
    }
    
    
    //Son_In.java
    package annotation.inherits;
    
    public class Son_In extends Father_In{
    }
    
    
  5. 编写测试类,利用反射机制获取运行时这几个类的注解

    package annotation.inherits;
    
    import java.lang.annotation.Annotation;
    
    public class Main {
        public static void main(String[] args) throws Exception{
            Annotation[] f_c = Class.forName("annotation.inherits.Father_Com").getAnnotations();
            Annotation[] s_c = Class.forName("annotation.inherits.Son_Com").getAnnotations();
            System.out.println(f_c.length);
            System.out.println(s_c.length);
    
            Annotation[] f_i = Class.forName("annotation.inherits.Father_In").getAnnotations();
            Annotation[] s_i = Class.forName("annotation.inherits.Son_In").getAnnotations();
            System.out.println(f_i.length);
            System.out.println(s_i.length);
        }
    }
    

    在这里插入图片描述
    分析:可以看到父类实现了Inherited元注解,子类继承该父类。反射加载时也能获得到这个注解。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值