您的位置:首页 > 编程语言 > Java开发

Eclipse+Selenium+Java环境配置

2013-01-11 13:44 441 查看
告知编译程序如何处理@Retention:

java.lang.annotation.Retention型态可以在您定义Annotation型态时,指示编译程序该如何对待您的自定义Annotation型态。

预定义上编译程序会将Annotation信息留在.class文档中,但不被虚拟机读取,而仅用于编译程序或工具程序运行时提供信息。

java.lang.annotation.RetentionPolicy 有三个枚举类型:CLASS、RUNTIME、SOURCE

只有当Annotation被指示成RUNTIME时,在运行时通过反射机制才能被JVM读取,否则,JVM是读取不到这个Annotation的。

 

java 代码

package com.test;   

  

import java.lang.annotation.Retention;   

import java.lang.annotation.RetentionPolicy;   

  

@Retention(RetentionPolicy.RUNTIME)   

public @interface RetentionTest {   

    String hello() default "hello";   

    String world();   

}   

 

java 代码

package com.test;   

  

public class MyTest {   

    @RetentionTest(hello = "beijing", world = "shanghai")   

    @Deprecated  

    @SuppressWarnings("unchecked")   

    public void output()   

    {   

        System.out.println("output");   

    }   

}   

 

java 代码

package com.test;   

  

import java.lang.annotation.Annotation;   

import java.lang.reflect.Method;   

  

public class ReflectRetentionTest {   

  

    public static void main(String[] args) throws Exception{   

        MyTest mt = new MyTest();   

        Class<mytest></mytest> c = MyTest.class;   

        Method method = c.getMethod("output",new Class[]{});   

        if(method.isAnnotationPresent(RetentionTest.class))   

        {   

            method.invoke(mt, new Object[]{});//output   

               

            RetentionTest  retentionTest = method.getAnnotation(RetentionTest.class);   

               

            System.out.println(retentionTest.hello());//beijing   

            System.out.println(retentionTest.world());//shanghai   

        }   

           

        Annotation[] annotations = method.getAnnotations();   

        for(Annotation annotation: annotations)   

        {   

            System.out.println(annotation.annotationType().getName());   

        }   

        //for循环里输出的结果是com.test.RetentionTest以及java.lang.Deprecated,而没有出来java.lang.SuppressWarnings   

        //因为java.lang.SuppressWarnings的Retention是被设置成RetentionPolicy.SOURCE类型的,所以在运行时是不会被虚拟机读取的。   

    }   

}   

运行第三个程序
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: