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.