【问题标题】:@Inherited annotation in JavaJava中的@Inherited注解
【发布时间】:2014-10-08 16:08:12
【问题描述】:

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 的注释,我不熟悉它。

【问题讨论】:

    标签: java inheritance annotations


    【解决方案1】:

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

    它只影响将用于类声明

    的注释

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

    这是一个。

    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

    【讨论】:

      猜你喜欢
      • 2014-07-21
      • 1970-01-01
      • 2017-06-04
      • 2011-08-01
      • 2011-03-08
      • 1970-01-01
      • 1970-01-01
      • 2013-09-09
      • 1970-01-01
      相关资源
      最近更新 更多