类
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.validation.constraints.*;
import java.io.Serializable;
@Getter
@Setter
@ToString
public class User implements Serializable {
@NotNull
@Min(value = 18, message = "年龄不能小于18")
@Max(value = 60, message = "年龄不能大于60")
private Integer age;
@NotNull(message = "name不能为空")
private String name;
@Size(min = 5, max = 10, message = "长度必须在5~10之间")
private String length;
@NotNull(message = "时间戳不能为空")
@Pattern(message = "时间格式不正确", regexp = "^((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))0229))([0-1]?[0-9]|2[0-3])([0-5][0-9])([0-5][0-9])$")
private String timeStamp;
}
参数校验工具类
import javax.validation.constraints.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
public class ValidationUtils {
public static void constraints(Object object) throws Exception {
if (object == null) {
throw new BizException(ResponseCode.PARAM_ERROR);
}
//获取该类的所有成员变量(私有的)
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
Annotation[] annotations = field.getAnnotations();
for (Annotation annotation : annotations) {
field.setAccessible(true);
if (annotation instanceof NotNull){
if (field.get(object) == null || "".equals(field.get(object))){
throw new BizException(ResponseCode.PARAM_ERROR,((NotNull) annotation).message());
}
}
if (annotation instanceof Min){
if (Integer.parseInt(field.get(object).toString()) <((Min) annotation).value()){
throw new BizException(ResponseCode.PARAM_ERROR,((Min) annotation).message());
}
}
if (annotation instanceof Max){
if (Integer.parseInt(field.get(object).toString()) >((Max) annotation).value()){
throw new BizException(ResponseCode.PARAM_ERROR,((Max) annotation).message());
}
}
if (annotation instanceof Size){
if (field.get(object).toString().length() < ((Size) annotation).min() || field.get(object).toString().length() > ((Size) annotation).max()){
throw new BizException(ResponseCode.PARAM_ERROR,((Size) annotation).message());
}
}
if (annotation instanceof Pattern){
if (!java.util.regex.Pattern.matches(((Pattern) annotation).regexp(), field.get(object).toString())){
throw new BizException(ResponseCode.PARAM_ERROR, ((Pattern) annotation).message());
}
}
}
}
}
}