用于某些特殊的参数校验
1.自定义注解@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NotNull {
//字段名称
String name() default "字段";
//提示信息
String message() default "不能为空";
}
2.被校验的实体
public class User {
@NotNull(name="学号" message = "不能为空")
public String id;
@NotNull(name="姓名" message = "不能为空")
public String name;
}
3.校验逻辑示例
public class ParamValid {
public static check(Object obj) throws Throwable {
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
boolean note = field.isAnnotationPresent(NotNull.class);
if (note) {
NotNull notNull = field.getAnnotation(NotNull.class);
String annoName = notNull.name();
String annomessage = notNull.message();
String fieldName = field.getName();
ObjectMapper mapper=new ObjectMapper();
String json = mapper.writeValueAsString(body);
Object fileValue = new Gson().fromJson(json, Map.class).get(fieldName);
if(StringUtils.isEmpty(fileValue ))){
throw new RuntimeException(annoName +annomessage);
}
}
}
}
}
4.在需要处进行校验
ParamValid.check(obj);