`

有关Annotation的继承

阅读更多

有关Annotation的继承说明:

1、JDK文档中的说明是:只有在类上应用的Annotation才能被继承,而实际应用时的结果是:除了类上应用的Annotation能被继承外,没有被重写的方法的Annotation也能被继承。

2、要注意的是:当方法被重写后,Annotation将不会被继承

3、要使得Annotation 被继承,需要在Annotation中加标识@Inherited,并且如果要被反射应用的话,就需要还有个@Retention(RetentionPolicy.RUNTIME) 标识

4、Annotation的继承不能应用在接口上

代码一、实现类上的继承

java 代码
  1. package com.test;   
  2.   
  3. import java.lang.annotation.Inherited;   
  4. import java.lang.annotation.Retention;   
  5. import java.lang.annotation.RetentionPolicy;   
  6.   
  7. @Inherited  
  8. @Retention(RetentionPolicy.RUNTIME)   
  9. public @interface InheritedTest {   
  10.     String hello();   
  11. }   

 

java 代码
  1. package com.test;   
  2.   
  3. @InheritedTest(hello = "yahaitt")   
  4. public class InheritedParent {   
  5.   
  6. }   

 

java 代码
  1. package com.test;   
  2.   
  3. public class InheritedChild extends InheritedParent {   
  4.   
  5. }   

 

java 代码
  1. package com.test;   
  2.   
  3. public class InheritedClassTest {   
  4.   
  5.     public static void main(String[] args) throws Exception   
  6.     {   
  7.         Class c = InheritedChild.class;   
  8.         if(c.isAnnotationPresent(InheritedTest.class))   
  9.         {   
  10.             InheritedTest it = c.getAnnotation(InheritedTest.class);   
  11.             System.out.println(it.hello());//yahaitt   
  12.         }   
  13.     }   
  14. }   

 

代码二、实现方法上的继承

java 代码
  1. package com.test;   
  2.   
  3. import java.lang.annotation.Inherited;   
  4. import java.lang.annotation.Retention;   
  5. import java.lang.annotation.RetentionPolicy;   
  6.   
  7. @Inherited  
  8. @Retention(RetentionPolicy.RUNTIME)   
  9. public @interface InheritedTest {   
  10.     String hello();   
  11. }   

 

java 代码
  1. package com.test;   
  2.   
  3.   
  4. public class InheritedParent {   
  5.   
  6.     @InheritedTest(hello = "yahaitt")   
  7.     public void doSomething()   
  8.     {   
  9.         System.out.println("parent do something");   
  10.     }   
  11.        
  12. }   

 

java 代码
  1. package com.test;   
  2.   
  3. public class InheritedChild extends InheritedParent {   
  4.        
  5.        
  6. }   

 

java 代码
  1. package com.test;   
  2.   
  3. import java.lang.reflect.Method;   
  4.   
  5. public class InheritedClassTest {   
  6.   
  7.     public static void main(String[] args) throws Exception   
  8.     {   
  9.         Class c = InheritedChild.class;   
  10.         Method method = c.getMethod("doSomething"new Class[]{});   
  11.         if(method.isAnnotationPresent(InheritedTest.class))   
  12.         {   
  13.             InheritedTest it = method.getAnnotation(InheritedTest.class);   
  14.             System.out.println(it.hello());//yahaitt   
  15.         }   
  16.     }   
  17. }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics