自定义字段注解
自定义字段描述
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldDescrib { String name(); String desc() default ""; } @Data public class StudentDemo { @FieldDescrib(name = "学生的年纪", desc = "正常情况是1-100") private Integer age; @FieldDescrib(name = "学生的性别", desc = "0:未知 1:男 2:女") private Integer sex; }
获取字段自定义注解
@RequestMapping("/getAttrVals") public void getAttrVal() { StudentDemo StudentDemo = new StudentDemo(); StudentDemo.setAge(20); StudentDemo.setSex(1); Field[] fields = StudentDemo.getClass().getDeclaredFields(); String getFields = ""; for (Field field : fields) { FieldDescrib declaredAnnotation = field.getDeclaredAnnotation(FieldDescrib.class); System.out.println(declaredAnnotation); getFields += "name:" + field.getName() + "=" + ModelToMap.getFieldValueByName(field.getName(), StudentDemo) + ","; } System.out.println(getFields.substring(0, getFields.length() - 1)); }
输出:
@com.demo.common.FieldDescrib(desc=正常情况是1-100, name=学生的年纪)
@com.demo.common.FieldDescrib(desc=0:未知 1:男 2:女, name=学生的性别)
name:age=20,name:sex=1
可以动态实现一些自定义的功能。