Annotation中的@Inherited

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.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章