zoukankan      html  css  js  c++  java
  • JAVA注解的使用

    应用场景:

    我们在通过一个key值取得其对应的值时,很容易想到用HashMap,或者用enmu, 但这两者都有不方便的地方,往往要加一大段代码,如果能用注解来搞定,不仅能省很多代码,且看上去也很直接,实现方法如下:

    1.先定义一个注解:

    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface TestAnnotation {	
    	public String description() default "";
    }
    

     定义了一个叫TestAnnotation的注解,其有个属性是description, 默认值是""

    2.接下来,我们就可以把这个注解应用上去了:

    public class Demo {	
    	
    	@TestAnnotation(description="hello world")
    	public final static String name = "zf";	
    	
    }
    

     3.接下来要做的事就是通过反射来获取其description了:

    import java.lang.reflect.Field;
    
    public class DescAnnotation {
    
    	public static <T> String getDescription(Class<T> klass, String str) {
    		Field[] f = klass.getFields();
    		for (Field field : f) {
    			String v = null;
    			try {
    				v = field.get(klass).toString();
    			} catch (IllegalArgumentException e) {				
    				e.printStackTrace();
    			} catch (IllegalAccessException e) {				
    				e.printStackTrace();
    			}			
    			if (field.isAnnotationPresent(TestAnnotation.class)	&& str.equals(v)) {
    				TestAnnotation desc = field.getAnnotation(TestAnnotation.class);
    				String d = desc.description();
    				return d;
    			}
    		}
    		return null;
    	}
    
    	public static void main(String[] args) {
    		System.out.println(DescAnnotation.getDescription(Demo.class, Demo.name));
    		System.out.println(DescAnnotation.getDescription(Demo.class, "zf"));
    	}
    
    }
    

     以上就是全部代码,我相信在自动化测试中,有很多的地方应用到我们自定义的注解,大家慢慢去体会吧!

  • 相关阅读:
    Android控件之ListView探究二
    解决activity页面跳转时显示桌面
    TextView实现滚动显示的效果
    QPainter的坐标系系统的转换
    MODBUS_RTU通信协议
    收藏的博客 -- Qt有关的GitHub/Gitee开源项目
    VS联调多个解决方案的项目
    软件工具——GitGUI使用教程
    Python中对文件的操作
    VMware虚拟机三种网络模式详解 --------- NAT(地址转换模式)
  • 原文地址:https://www.cnblogs.com/zhangfei/p/4268420.html
Copyright © 2011-2022 走看看