实例类:
@Data
public class Person{
@NotNull(message = "姓名不能为空")
private String personName;
@NotNull(message = "年龄不能为空")
private Integer personAge;
@NotNull(message = "性别不能为空")
private String personSex;
private String personId;
private String personEmail;
}
校验方法:
@Slf4j
public class BaseVerify{
protected void paramVerify(Person person) {
try{
//获取对象所有参数
Field[] fields = person.getClass().getDeclaredFields();
for (Field field : fields){
NotNull annotation = field.getAnnotation(NotNull.class);
if (ObjectUtil.isNotNull(annotation)){
//设置允许访问私有属性
field.setAccessible(Boolean.TRUE);
Object value = field.get(t);
//判断该参数是否为空
if (ObjectUtil.isEmpty(value)){
log.warn("缺失必选参数");
//抛出自定义异常
throw new PersonException("参数不能为空");
}
}
} catch(IllegalAccessException e){
log.warn("解析数据异常",e);
}
}
}
Person person = new Person();
person.setPersonName("xiaoming");
person.setPersonAge(18);
person.setPersonId("1234567");
paramVerify(person);
}



