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"));
	}

}

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

原文地址:https://www.cnblogs.com/zhangfei/p/4268420.html