告知编译程序如何处理@Retention

告知编译程序如何处理@Retention:

java.lang.annotation.Retention型态可以在您定义Annotation型态时,指示编译程序该如何对待您的自定义Annotation型态。

预定义上编译程序会将Annotation信息留在.class文档中,但不被虚拟机读取,而仅用于编译程序或工具程序运行时提供信息。

java.lang.annotation.RetentionPolicy 有三个枚举类型:CLASS、RUNTIME、SOURCE

只有当Annotation被指示成RUNTIME时,在运行时通过反射机制才能被JVM读取,否则,JVM是读取不到这个Annotation的。

 

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

 

java 代码
  1. package com.test;   
  2.   
  3. public class MyTest {   
  4.     @RetentionTest(hello = "beijing", world = "shanghai")   
  5.     @Deprecated  
  6.     @SuppressWarnings("unchecked")   
  7.     public void output()   
  8.     {   
  9.         System.out.println("output");   
  10.     }   
  11. }   

 

java 代码
  1. package com.test;   
  2.   
  3. import java.lang.annotation.Annotation;   
  4. import java.lang.reflect.Method;   
  5.   
  6. public class ReflectRetentionTest {   
  7.   
  8.     public static void main(String[] args) throws Exception{   
  9.         MyTest mt = new MyTest();   
  10.         Class c = MyTest.class;   
  11.         Method method = c.getMethod("output",new Class[]{});   
  12.         if(method.isAnnotationPresent(RetentionTest.class))   
  13.         {   
  14.             method.invoke(mt, new Object[]{});//output   
  15.                
  16.             RetentionTest  retentionTest = method.getAnnotation(RetentionTest.class);   
  17.                
  18.             System.out.println(retentionTest.hello());//beijing   
  19.             System.out.println(retentionTest.world());//shanghai   
  20.         }   
  21.            
  22.         Annotation[] annotations = method.getAnnotations();   
  23.         for(Annotation annotation: annotations)   
  24.         {   
  25.             System.out.println(annotation.annotationType().getName());   
  26.         }   
  27.         //for循环里输出的结果是com.test.RetentionTest以及java.lang.Deprecated,而没有出来java.lang.SuppressWarnings   
  28.         //因为java.lang.SuppressWarnings的Retention是被设置成RetentionPolicy.SOURCE类型的,所以在运行时是不会被虚拟机读取的。   
  29.     }   
  30. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值