JAVA注解的使用
应用场景:
我们在通过一个 key 值取得其对应的值时,很容易想到用 HashMap,或者用 enmu, 但这两者都有不方便的地方,往往要加一大段代码,如果能用注解来搞定,不仅能省很多代码,且看上去也很直接,实现方法如下:
1. 先定义一个注解:
1 2 3 4 5 6 7 8 9 10 | 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. 接下来,我们就可以把这个注解应用上去了:
1 2 3 4 5 6 | public class Demo { @TestAnnotation (description= "hello world" ) public final static String name = "zf" ; } |
3. 接下来要做的事就是通过反射来获取其 description 了:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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" )); } } |
以上就是全部代码,我相信在自动化测试中,有很多的地方应用到我们自定义的注解,大家慢慢去体会吧!