现在的位置: 首页 > 综合 > 正文

子类是否继承父类的 annotation – Inherited

2013年01月25日 ⁄ 综合 ⁄ 共 1305字 ⁄ 字号 评论关闭

在网上搜索到这样一篇文章,内容如下:

---------------转帖开始----------------

 

在您定义Annotation型态后并使用于程式码上时,预设上父类别中的Annotation并不会被继承至子类别中,您可以在定义 Annotation时加上java.lang.annotation.Inherited的Annotation,这让您定义的Annotation型别被继承下来。

例如:

  • Debug.java
  1. package onlyfun.caterpillar;
  2. import java.lang.annotation.Retention;
  3. import java.lang.annotation.RetentionPolicy;
  4. import java.lang.annotation.Inherited;
  5. @Retention(RetentionPolicy.RUNTIME)
  6. @Inherited
  7. public @interface Debug {
  8.     String value();
  9.     String name();

在下面这个程式中使用它:

  • SomeObject.java
  1. package onlyfun.caterpillar;
  2. public class SomeObject {
  3.     @Debug(
  4.        value = "unit",
  5.        name = "debug1"
  6.     )
  7.     public void doSomething() {
  8.           // ....    
  9.     }

如果您有一个类别继承自SomeObject,则理想上@Debug也会被继承下来,不过事实上Inherited在Sun JDK 5.0中还没有作用。

---------------转帖结束----------------

 

该文作者写这篇文章时没有认真阅读jdk文档,

 

请看jdk中原文:

  1. Note that this meta-annotation type has no effect if the annotated type is used to annotate anything other than a class. Note also that this meta-annotation only causes annotations to be inherited from superclasses; annotations on implemented interfaces have no effect. 

意思即为:

注意,如果使用注释类型注释类以外的任何事物,此元注释类型都是无效的。还要注意,此元注释仅促成从超类继承注释;对已实现接口的注释无效。

 

就是说,注释继承只能是针对类的注释,其他的都不起作用。

 

经过本人测试,如果子类只是继承父类,而不覆写(Override)对应的使用了inherited注解的方法,则子类依然是会继承父类对应方法的注释的;否则如果子类覆写(Override)了该方法,则对应的注解同样会被覆盖掉,即此时父类方法的注解将不被子类方法所继承。

抱歉!评论已关闭.