父接口中的注解的继承性(对应的类元素:接口,属性,默认方法,抽象方法)

主要讨论两点:
1.基于接口的继承/实现中,属性和方法注解的继承性
2.基于元注解@Inherited,接口上注解的继承性

以demo为例:

 class IterInheritedTest {

    @Target(value = {ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
    @Retention(value = RetentionPolicy.RUNTIME)
    @Inherited // 声明注解具有继承性
    @interface DESC {
        String value() default "";
    }

    @DESC("父接口上的注解")
    interface SuperInterface {
        @DESC("父接口的属性")
        String field = "field";
        @DESC("父接口方法foo")
        void foo();
        @DESC("父接口方法bar")
        default void bar() {

        }
    }


    interface ChildInterface extends SuperInterface {
        @DESC("子接口方法foo")
        @Override
        void foo();
    }

     class ChildClass implements SuperInterface {
        @DESC("子类的属性")
        public String field = "field";
        @Override
        public void foo() {
        }
    }

    public static void main(String[] args) throws NoSuchMethodException, NoSuchFieldException {
        //子接口重写方法
        Method iFoo = ChildInterface.class.getMethod("foo");
        System.out.println(Arrays.toString(iFoo.getAnnotations()));
        
        //子接口继承方法
        Method iBar = ChildInterface.class.getMethod("bar");
        System.out.println(Arrays.toString(iBar.getAnnotations()));

        //子接口继承属性
        Field iField = ChildInterface.class.getField("field");
        System.out.println(Arrays.toString(iField.getAnnotations()));

        //实现类重写方法
        Method foo = ChildClass.class.getMethod("foo");
        System.out.println(Arrays.toString(foo.getAnnotations()));

        //实现类继承方法
        Method bar = ChildClass.class.getMethod("bar");
        System.out.println(Arrays.toString(bar.getAnnotations()));

        //实现类作用域下的同名属性
        Field field = ChildClass.class.getField("field");
        System.out.println(Arrays.toString(field.getAnnotations()));
   
        //实现类类上
        System.out.println(Arrays.toString(ChildClass.class.getAnnotations()));  
        //子接口接口上
        System.out.println(Arrays.toString(ChildInterface.class.getAnnotations()));  

    }
}

运行结果:
在这里插入图片描述

可以得出一些结论
1.基于接口的继承/实现中,属性和方法注解的继承忠实于方法/属性继承本身,客观反映方法/属性上的注解(即直接继承的,以父接口为准,重写的,以子接口或实现类为准)。另外jdk7以前接口的方法因为都是抽象方法,都需要重写实现,所以子类中的方法永远也无法获得父接口方法的注解,但是jdk8以后的默认方法打开了这种限制。
2.基于元注解@Inherited,接口上注解的继承性:实现类或子接口无法继承父接口接口上的注解,这点与类是不同的。

参考:https://www.jianshu.com/p/a848655d478e

本人才疏学浅,如有错误,烦请指点,谢谢。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值