@Retention
来源:互联网 发布:音频后期制作软件手机 编辑:程序博客网 时间:2024/04/28 04:49
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
0 0
- @Retention
- @Retention
- @Retention:
- annotation(@Retention)
- RETENTION POLICY
- annotation(@Retention)
- @Retention注解
- Backup Retention Policies
- CONFIGURE RETENTION POLICY
- oracle 之 Undo Retention
- undo retention详解【转】
- Java @Retention注解
- @Retention、RetentionPolicy源码翻译
- Java中的@Retention详解
- 元注解-@Retention&@Target
- annotation(@Retention@Target)详解
- RETENTION GUARANTEE 参数的作用
- Class and Runtime Retention Policy
- 当开发者产生一个伟大的想法之后应该做的10件事
- DevOPS世界的本质
- url动态参数
- pushbackDemo(Modalview present)
- php 错误与异常 error exception
- @Retention
- 基于TCP的TFTP(Trivial File Transfer Protocol,简单文件传输协议) 的c编程实现
- 文件读写操作总结
- 在django项目中加入像bootstrap这样的css,js等静态文件
- Webservice介绍,CXF入门程序
- Java Object类方法
- UVa10801_Lift Hopping(最短路)(小白书图论专题)
- C++虚函数
- 工作周报007