import com.pasc.medical.core.base.exception.BusinessException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils;
import javax.validation.*;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Set;
public class ValidateUtils {
/**
* 校验 Bean
* @param t
* @param <T>
* @return
*/
public static <T> String validate(T t){
ValidatorFactory vFactory = Validation.buildDefaultValidatorFactory();
Validator validator = vFactory.getValidator();
Set<ConstraintViolation<T>> set = validator.validate(t);
if (set.size() > 0) {
StringBuilder validateError = new StringBuilder();
int i = 1;
for (ConstraintViolation<T> val : set) {
validateError.append(val.getMessage());
if (i < set.size()) {
validateError.append(",");
}
i++;
}
return validateError.toString();
}
return null;
}
/**
* 校验 List 集合
* @param list
* @param param
* @param paramName
* @param <T>
*/
public static <T> void validate(List<T> list,String param,String paramName){
if(CollectionUtils.isEmpty(list)){
throw new BusinessException("101401","校验参数为空");
}
String validateStr;
StringBuilder validateBuilder = new StringBuilder();
for(T t : list){
validateStr = validate(t);
if(StringUtils.isNotBlank(validateStr)){
validateBuilder.append(paramName).append(":")
.append(getParamValue(t,param)).append(",")
.append(validateStr.toString()).append("\n");
}
}
// 有异常直接抛出异常
if(validateBuilder.length() > 0){
throw new BusinessException("101402",validateBuilder.toString());
}
}
public static <T> Object getParamValue(T t,String param){
Field field = ReflectionUtils.findField(t.getClass(),param);
field.setAccessible(true);
Object value = ReflectionUtils.getField(field,t);
return value;
}
}
网友评论