有关Annotation的继承说明:
1、JDK文档中的说明是:只有在类上应用的Annotation才能被继承,而实际应用时的结果是:除了类上应用的Annotation能被继承外,没有被重写的方法的Annotation也能被继承。
2、要注意的是:当方法被重写后,Annotation将不会被继承。
3、要使得Annotation 被继承,需要在Annotation中加标识@Inherited,并且如果要被反射应用的话,就需要还有个@Retention(RetentionPolicy.RUNTIME) 标识
4、Annotation的继承不能应用在接口上
代码一、实现类上的继承
java 代码
- package com.test;
- import java.lang.annotation.Inherited;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- @Inherited
- @Retention(RetentionPolicy.RUNTIME)
- public @interface InheritedTest {
- String hello();
- }
java 代码
- package com.test;
- @InheritedTest(hello = "yahaitt")
- public class InheritedParent {
- }
java 代码
- package com.test;
- public class InheritedChild extends InheritedParent {
- }
java 代码
- package com.test;
- public class InheritedClassTest {
- public static void main(String[] args) throws Exception
- {
- Class c = InheritedChild.class;
- if(c.isAnnotationPresent(InheritedTest.class))
- {
- InheritedTest it = c.getAnnotation(InheritedTest.class);
- System.out.println(it.hello());//yahaitt
- }
- }
- }
代码二、实现方法上的继承
java 代码
- package com.test;
- import java.lang.annotation.Inherited;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- @Inherited
- @Retention(RetentionPolicy.RUNTIME)
- public @interface InheritedTest {
- String hello();
- }
java 代码
- package com.test;
- public class InheritedParent {
- @InheritedTest(hello = "yahaitt")
- public void doSomething()
- {
- System.out.println("parent do something");
- }
- }
java 代码
- package com.test;
- public class InheritedChild extends InheritedParent {
- }
java 代码
- package com.test;
- import java.lang.reflect.Method;
- public class InheritedClassTest {
- public static void main(String[] args) throws Exception
- {
- Class c = InheritedChild.class;
- Method method = c.getMethod("doSomething", new Class[]{});
- if(method.isAnnotationPresent(InheritedTest.class))
- {
- InheritedTest it = method.getAnnotation(InheritedTest.class);
- System.out.println(it.hello());//yahaitt
- }
- }
- }