飙血推荐
  • HTML教程
  • MySQL教程
  • JavaScript基础教程
  • php入门教程
  • JavaScript正则表达式运用
  • Excel函数教程
  • UEditor使用文档
  • AngularJS教程
  • ThinkPHP5.0教程

annotation(@Retention)的学习

时间:2021-12-14  作者:匿名  

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

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

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

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

例子:

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

package test;  
  
import 域名域名ntion;  
import 域名域名ntionPolicy;  
  
@Retention(域名IME)  
public @interface MyAnnotation {  
    String hello() default "sunqitang";  
    String world();  
}

第二步:建立一个域名 来使用上面的annotation。

public class MyTest {  
    @MyAnnotation(world="Hello,world!",hello="域名!")  
    public void output(){  
        域名tln("output is running");  
    }  
}

第三步:用反射机制来调用注解中的内容

import 域名域名tation;  
import 域名域名od;  
  
public class MyReflection  {  
    public static void main(String[] args) throws Exception {  
        Class<MyTest> c = 域名s;//获得要调用的类  
        Method method = 域名ethod("output", new Class[]{});//获得要调用的方法,output为要调用方法名字,new Class[]{}为所需要的参数。由于为空,所以使用这个方式  
        if(域名notationPresent(域名s)){//是否有类型为MyAnnotation的注解  
            MyAnnotation annotation = 域名nnotation(域名s);//获得注解  
            域名tln(域名o()); //调用注解内容  
            域名tln(域名d());//调用注解内容  
        }  
        域名tln("------------------------");  
        Annotation[] annotations = 域名nnotations();//获得所有注解。必须是在runtime类型的。  
        for(Annotation annotation: annotations){//遍历所以注解的名称  
            域名tln(域名tationType().getName());  
        }  
    }  
}

运行结果

Hello,beijing!
域名
------------------------ 域名notation
湘ICP备14001474号-3  投诉建议:234161800@qq.com   部分内容来源于网络,如有侵权,请联系删除。