java 1.5中提供了对annotation的支持,其中内置提供的@Inherited一直没有太注意。这次在开发中碰到了一个问题,才算真正理解了。
1、@Inherited的定义
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
}根据Target的定义我们,我们知道了@Inherited只用于Annotation Type的定义当中。例如:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Foo {
String value() default "";
}
2、作用
是用来指示Annotation Type是自动继承的。举例说明
@Foo
public class Parent {}
public class Sub extends Parent {}Sub.class.isAnnotationPresent(Foo.class)返回true。我们看到,在Sub类上,没有@Foo,但是因为有Foo有Inherited存在,所以就会在父类当中去查找,这个过程会重复,只到Foo被找到或达到类的层次结构的最顶端。还是没有找到,就返回false.
3、注意事项
如果Parent为接口
@Foo
public interface Parent {}
public class Sub implements Parent {}Sub.class.isAnnotationPresent(Foo.class)返回false。
4、结论
接口上的annotation是不能继承的;
类上的annotation是可以继承的,但annotation定义当中必须包含@Inherited.
本文详细介绍了Java 1.5中引入的@Inherited注解,解释了其使用场景及注意事项,包括如何实现注解的继承特性,并强调了在类与接口中的不同表现。
908

被折叠的 条评论
为什么被折叠?



