现在,我们对 InheritableSon.java 进行修改:注释掉 "Inheritable 的 @Inherited 注解"。
InheritableSon.java
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Inherited;
/**
* 自定义的Annotation。
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
//@Inherited
@interface Inheritable
{
}
@Inheritable
class InheritableFather
{
public InheritableFather() {
// InheritableBase是否具有 Inheritable Annotation
System.out.println("InheritableFather:"+InheritableFather.class.isAnnotationPresent(Inheritable.class));
}
}
/**
* InheritableSon 类只是继承于 InheritableFather,
*/
public class InheritableSon extends InheritableFather
{
public InheritableSon() {
super(); // 调用父类的构造函数
// InheritableSon类是否具有 Inheritable Annotation
System.out.println("InheritableSon:"+InheritableSon.class.isAnnotationPresent(Inheritable.class));
}
public static void main(String[] args)
{
InheritableSon is = new InheritableSon();
}
}
运行结果:
InheritableFather:true
InheritableSon:false
对比上面的两个结果,我们发现:当注解 Inheritable 被 @Inherited 标注时,它具有继承性。否则,没有继承性。