annotation(@Retention)

Retention型态可以在您定义Annotation型态时,指示编译程序该如何对待您的自定义的Annotation型态。预设上编译程序会将Annotation信息留在.class档案中,但不被虚拟机读取,而仅仅用于编译程序或工具程序运行时提供信息。


在使用Retention时必须要提供一个RetentionPolicy的枚举类型参数。

RetentionPolicy有三个枚举内容:CLASS RUNTIME SOURCE
     SOURCE, //编译程序处理完Annotation信息后就完成任务
     CLASS,  //编译程序将Annotation储存于class档中,缺省
     RUNTIME //编译程序将Annotation储存于class檔中,可由VM读入(通过反射机制)。这个功能搭配反射是非常强大的。

 

当使用@Retention时要记得加参数和加入"包"。

 

例子:

   第一步:新建一个annotation,名字为:MyAnnotation.java。注意引入了Retention和RetentionPolicy这两个包

package test;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
	String hello() default "sunqitang";
	String world();
}

   第二步:建立一个MyTest.java 来使用上面的annotation。

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());
		}
	}
}

 运行结果:

Hello,beijing!
Hello,world!
------------------------
test.MyAnnotation
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值