zoukankan      html  css  js  c++  java
  • @Retention小记

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

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

    RetentionPolicy 有三个枚举类型:

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

    例子:

    第一步:新建一个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

    记录点滴,是对知识理解的阐述与理解,也是对知识的沉淀与回顾;或肤浅、或错误亦是成长与进步,当自得其乐;如若有幸得各路大神不吝赐教,当欣喜异常、不胜感激!
  • 相关阅读:
    正则表达式
    Newtonsoft.Json
    MVC之参数验证(三)
    MVC之参数验证(二)
    MVC之参数验证(一)
    MVC之模型绑定
    导致存储过程重新编译的原因
    IFormattable,ICustomFormatter, IFormatProvider接口
    oracle将id串转换为名字串
    oracle查看表空间大小及使用情况
  • 原文地址:https://www.cnblogs.com/francis-alice/p/3977670.html
Copyright © 2011-2022 走看看