import org.springframework.util.CollectionUtils; import javax.validation.ConstraintViolation; import javax.validation.Valid; import javax.validation.Validation; import java.util.Set; /** * 手动调用api方法校验对象 */ public class MyValidationUtils { public static String validate(@Valid Object user) { Set<ConstraintViolation<@Valid Object>> validateSet = Validation.buildDefaultValidatorFactory().getValidator().validate(user, new Class[0]); if (!CollectionUtils.isEmpty(validateSet)) { String messages = validateSet.stream() .map(ConstraintViolation::getMessage) .reduce((m1, m2) -> m1 + ";" + m2) .orElse("参数输入有误!"); return messages; } return null; } public static String validate(@Valid Object user,Class clas) { Set<ConstraintViolation<@Valid Object>> validateSet = Validation.buildDefaultValidatorFactory().getValidator().validate(user, clas); if (!CollectionUtils.isEmpty(validateSet)) { String messages = validateSet.stream() .map(ConstraintViolation::getMessage) .reduce((m1, m2) -> m1 + ";" + m2) .orElse("参数输入有误!"); return messages; } return null; } }
标签:validateSet,Java,String,手动,messages,m1,import,validate From: https://www.cnblogs.com/firelang/p/16783373.html