[英]@Inherited annotation in Java
Herbert Schildt在他关于Java的书中提到过,
@Inherited
是一个标记注释,只能用于另一个注释声明。 此外,它仅影响将在类声明上使用的注释。@Inherited
使超类的注释由子类继承。因此,当对子类进行特定注释的请求时,如果子类中不存在该注释,则检查其超类。 如果该注释存在于超类中,并且如果使用
@Inherited
注释,则将返回该注释。
我很清楚注释不是继承的。 例外是注释,其声明用@Inherited
注释。
我已经明白其中包括java.lang.annotation中的注释的休息: @Retention
, @Documented
和@Target
。 和其他三个@Override
@Deprecated
, @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的注释的上下文中解释我,我不熟悉它。
首先,正如您发布的报价所述,
它仅影响将在类声明上使用的注释
因此,您的示例不适用,因为您正在注释方法。
这是一个。
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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.