告知编译程序如何处理@Retention
java.lang.annotation.Retention型态可以在您定义Annotation型态时,指示编译程序该如何对待您的自定义Annotation型态。
预设上编译程序会将Annotation信息留在.class档案中,但不被虚拟机读取,而仅用于编译程序或工具程序运行时提供信息。
在使用Retention型态时,需要提供java.lang.annotation.RetentionPolicy的枚举型态:
package java.lang.annotation;
public enum RetentionPolicy{
       SOURCE;  //编译程序处理完Annotation后就完成任务
       CLASS;    //编译程序将Annotation储存于class档中,缺省
       RUNTIME; //编译程序将Annotation储存于class档中,可由VM读入
}
<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

 

RetentionPolicySOURCE的例子是@SuppressWarnings,仅在编译时期告知编译程序来抑制警告,所以不必将这个信息储存于.class档案。
RetentionPolicyRUNTIME的时机,可以像使用java设计一个程序代码分析工具,您必须让vm能读出Annotation信息,以便在分析程序时使用。
搭配反射(Reflection)机制,应可以达到这个目的。

 

java.lang.reflect.AnnotatedElement接口:
public Annotation getAnnotation(Class annotationType);
public Annotation[] getAnnotations();
public Annotation[] getDeclaredAnnotations();
public Boolean isAnnotationPresent(Class annotationType);

 

ClassConstructorFieldMethodPackage等类别,都实现了AnnotatedElement接口。

 

定义:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

 

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation{
              String hello() default:”wangsy”;
       String world();
}

 

使用:
public class MyTest{
       @MyAnnotation(hello=”<?xml:namespace prefix = st1 ns = "urn:schemas-microsoft-com:office:smarttags" />beijing”,world=”shangshi”)
       public void output(){
       System.out.println(“output something”);
}
}
利用反射机制读取Annotation信息
public class MyReflection{
       public static void main(String[] args){
       MyTest myTest = new MyTest();
      
       Class<MyTest> c = myTest.class;
       //得到output方法
       Method method = c.getMethod(“output”,new Class[]{});

 

       if (method.isAnnotationPresent(MyAnnotation.class)){
       method.invoke(myTest,new Object[]{});
       MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);

 

       String hello = myAnnotation.hello();
       String world = myAnnotation.world();
      
       System.out.println(hello);
       System.out.println(world);
}

 

Annotation[] annotations = method.getAnnotations();

 

for (Annotation annotation:annotations){
       System.out.println(annotation.annotationType().getName());
}
}
}