@Java中的继承注释
Herbert Schildt在他关于Java的书中提到@Java中的继承注释,java,inheritance,annotations,Java,Inheritance,Annotations,Herbert Schildt在他关于Java的书中提到 @Inherited是一个标记批注,只能在另一个批注声明上使用。此外,它只影响将在类声明上使用的注释@Inherited导致子类继承超类的注释 因此,当对子类发出特定注释的请求时,如果该注释不在子类中,则检查其超类。如果超类中存在该注释,并且使用继承的@对其进行注释,则将返回该注释 我很清楚注释不是继承的。例外是注释,其声明用@Inherited注释 我已经理解了其余的注释,包括java.lang.annotation:@Retentio
@Inherited
是一个标记批注,只能在另一个批注声明上使用。此外,它只影响将在类声明上使用的注释@Inherited
导致子类继承超类的注释
因此,当对子类发出特定注释的请求时,如果该注释不在子类中,则检查其超类。如果超类中存在该注释,并且使用继承的@对其进行注释,则将返回该注释
我很清楚注释不是继承的。例外是注释,其声明用@Inherited
注释
我已经理解了其余的注释,包括java.lang.annotation:@Retention
、@Documented
和@Target
。和其他三个-@覆盖
,@弃用
,和@抑制警告
谈到@Inherited
注释,我有点困惑。有人能用一个简单的例子来演示一下吗
其次,在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(){}
}
当将@继承的注释放在注释@界面Baz
上时,它有什么用途
请不要在使用Spring框架的注释的上下文中解释我,我对它一点也不熟悉。首先,正如您发布的引用所述
它只影响将在类声明上使用的注释
因此,您的示例不适用,因为您正在注释方法
这里有一个
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