2017-5-13 by MartinDelophy
从读研开始做OA项目一晃将近半年了,一直在用到java方面的注解,愚钝的我直到现在才开始考虑到如何自定义注解,从网上看到了一个好例子,分享出来给需要帮助的人使用。
那么首先我们先做一个接口,这个接口的作用是作为注解引用的,里面做了一个枚举类型,定义了一个Tt()方法,默认值为C
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface test { public enum T{ A,B,C}; T Tt() default T.C; }
之后我们定义了一个 test2的类,外加一个主函数目的很简单,就是为了让test3去读我们test2的class类
public class test2 { @test(Tt= test.T.C) private String t; public static void main(String[] args) { test3.gettest(test2.class); } }
test3就是看test2的类中有没有test注解,有的话就是输出来看看
public class test3 { public static void gettest(Class<?> clazz) { String str=""; Field[] fields = clazz.getDeclaredFields(); for(Field field :fields) { if(field.isAnnotationPresent(test.class)){ test t=(test) field.getAnnotation(test.class); str=str+t.Tt(); System.out.println(str); } } } }
结果,控制台输出的是 C,因为一开始将枚举中,默认的C传入,再字符串拼接,显示