关于java中元注解Inherited 的使用说明
首先解释下元注解,就是用来中声明注解类型时需要使用到的注解。
Inherited作用是,使用此注解声明出来的自定义注解,在使用此自定义注解时,如果注解在类上面时,子类会自动继承此注解,否则的话,子类不会继承此注解。这里一定要记住,使用Inherited声明出来的注解,只有在类上使用时才会有效,对方法,属性等其他无效。
下面看下代码就明了了。
下面是输出结果
由上可以看出,通过Inherited元注解声明的自定义注解,在类上使用时,可以被子类继承,对第一个方法进行测试时,由于子类继承了父类方法,且两个都没有输出,证明Inherited对方法无效,由方法2可以看出,因为子类没有重写父类方法,所以是直接使用的父类方法,所以两个都会输出,同理属性也是,都会输出。
所以证明最后结论:通过对注解上使用元注解Inherited声明出的注解,在使用时用在类上,可以被子类所继承,对属性或方法无效。