@Inherited Java注释

时间:2014-10-08 16:08:13

标签: java inheritance annotations

Herbert Schildt在他关于Java的书中提及

  

@Inherited是一个标记注释,只能用于另一个注释声明。此外,它仅影响将在类声明上使用的注释。 @Inherited导致超类的注释被子类继承。

     

因此,当对子类进行特定注释的请求时,如果子类中不存在该注释,则检查其超类。如果该注释存在于超类中,并且使用@Inherited进行注释,则将返回该注释。

我很清楚注释不是继承的。例外是注释,其声明用@Inherited注释。

我已理解其余的注释,其中包括java.lang.annotation:@Retention@Documented@Target。和其他三个 - @Override@Deprecated@SuppressWarnings

对于@Inherited注释,我有点困惑。有人可以通过一个简单的foobar示例来演示它吗?

其次,在StackOverflow上经历了有关此问题的其中一个问题,我遇到了这个问题,

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) @Inherited
public @interface Baz { 
           String value(); }

public interface Foo{
    @Baz("baz") void doStuff();
}

public interface Bar{
    @Baz("phleem") void doStuff();
}

public class Flipp{
    @Baz("flopp") public void doStuff(){} 
}

@Inherited注释在注释@interface Baz上有什么用处?

请不要在使用Spring Framework的注释的上下文中解释我,我不熟悉它。

1 个答案:

答案 0 :(得分:10)

首先,正如您发布的报价所述,

  

它仅影响将在类声明

上使用的注释

因此,您的示例不适用,因为您需要注释方法。

这是一个。

public class Test {
    public static void main(String[] args) throws Exception {
        System.out.println(Bar.class.isAnnotationPresent(InheritedAnnotation.class));
    }
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
//@Inherited
@interface InheritedAnnotation {
}

@InheritedAnnotation
class Foo {

}

class Bar extends Foo {
}

这将打印false,因为CustomAnnotation未注明@Inherited。如果您取消注释使用@Inherited,则会打印true