主要讨论两点:
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,接口上注解的继承性:实现类或子接口无法继承父接口接口上的注解,这点与类是不同的。
本人才疏学浅,如有错误,烦请指点,谢谢。