java 引语
Retention型态可以在您定义Annotation型态时,指示编译程序该如何对待您的自定义的Annotation型态。
默认情况下是:编译程序会将此Annotation信息存在.class文件中,但是不能被虚拟机读取到信息,仅仅是用于编译程序或工具运行时提供信息而已。
在使用Retention时必须要提供一个RetentionPolicy的枚举类型参数。
RetentionPolicy有三个枚举内容:CLASS RUNTIME SOURCE
SOURCE, //编译程序处理完Annotation信息后就完成任务
CLASS, //编译程序将Annotation储存于class档中,缺省
RUNTIME //编译程序将Annotation储存于class檔中,可由VM读入(通过反射机制)。这个功能搭配反射是非常强大的。
请观察下面的事例---------------------------------------------------------------
创建注解
package test;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String hello() default "sunqitang";
String world();
}
创建使用注解的类
public class MyTest {
@MyAnnotation(world="Hello,world!",hello="Hello,beijing!")
public void output(){
System.out.println("output is running");
}
}
用反射机制来调用注解中的内容
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class MyReflection {
public static void main(String[] args) throws Exception {
Class<MyTest> c = MyTest.class;//获得要调用的类
Method method = c.getMethod("output", new Class[]{});//获得要调用的方法,output为要调用方法名字,new Class[]{}为所需要的参数。由于为空,所以使用这个方式
if(method.isAnnotationPresent(MyAnnotation.class)){//是否有类型为MyAnnotation的注解
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);//获得注解
System.out.println(annotation.hello()); //调用注解内容
System.out.println(annotation.world());//调用注解内容
}
System.out.println("------------------------");
Annotation[] annotations = method.getAnnotations();//获得所有注解。必须是在runtime类型的。
for(Annotation annotation: annotations){//遍历所以注解的名称
System.out.println(annotation.annotationType().getName());
}
}
}
------------------------------- Retention ----------------------END
// 注解适用地方(字段和方法)
@Target({ElementType.FIELD, ElementType.METHOD })
------------------------------------------------ Target -------------------------END