Java注解和注解处理器使用方法
原创:转载需注明原创地址 https://www.cnblogs.com/fanerwei222/p/11492274.html
准备材料:
实体类: PrintDemo
注解类: PrintName
注解处理器: AnnotationUtil
注解测试类: AnnotationMain
直接上代码:
package annotation; /** * TODO * 打印demo */ public class PrintDemo { @PrintName(print = true) private String what; @PrintName(print = false) private String noWhat; @PrintName(print = true) private String onThere; public String getWhat() { return what; } public void setWhat(String what) { this.what = what; } public String getNoWhat() { return noWhat; } public void setNoWhat(String noWhat) { this.noWhat = noWhat; } public String getOnThere() { return onThere; } public void setOnThere(String onThere) { this.onThere = onThere; } }
package annotation; import java.lang.annotation.*; /** * TODO * 打印字段名称 */ @Retention(RetentionPolicy.RUNTIME) @Documented @Target(ElementType.FIELD) public @interface PrintName { boolean print(); }
package annotation; import java.lang.reflect.Field; /** * TODO * 注解处理器工具类 */ public class AnnotationUtil { public static void executeAnnotaPrint(Class<?> clazz){ Field[] fields = clazz.getDeclaredFields(); for (Field field : fields){ if (field.isAnnotationPresent(PrintName.class) && field.getAnnotation(PrintName.class).print()){ System.out.println("通过注解打印字段的名称: " + field.getName()); } } } }
package annotation; /** * TODO * 注解main测试方法 */ public class AnnotationMain { public static void main(String[] args){ AnnotationUtil.executeAnnotaPrint(PrintDemo.class); } }
效果如下:
结束🔚