一:字段少的校验用法
Assert.notNull(payable, "Payable不能为空!");
Assert.notNull(payable.getNettingStatus(), "Payable.nettingStatus不能为空!");
一:字段多的校验用法(自己写了工具类)
/** * 校验对象属性 * * @author dy * JDK-version: JDK1.7 * @since 2017.5.22 */ public class ObjectUtils { private static final Logger logger = LoggerFactory.getLogger(ObjectUtils.class); /** * 校验对象属性均不能为空! * * @param obj * @return * @author DengYang */ public static boolean validField(Object obj) throws IllegalAccessException { if (obj == null) throw new IllegalAccessException("参数不能为空!"); for (Field field : obj.getClass().getDeclaredFields()) { field.setAccessible(true); if (StringUtils.isEmpty(field.get(obj))) { logger.error("==> " + field.getName() + "不能为空!"); throw new IllegalAccessException(field.getName() + "不能为空!"); } } return true; } /** * 指定字段名字,校验对象属性不能为空! * * @param obj * @return * @author DengYang */ public static boolean validFieldByFileldName(Object obj, String... fieldName) throws IllegalAccessException { if (obj == null) throw new IllegalAccessException("参数不能为空!"); if (fieldName == null || fieldName.length < 1) { throw new IllegalAccessException("fieldName参数不能为空!"); } for (Field field : obj.getClass().getDeclaredFields()) { field.setAccessible(true); for (String name : fieldName) { if (field.getName().equals(name)) { if (StringUtils.isEmpty(field.get(obj))) { logger.error("==> " + field.getName() + "不能为空!"); throw new IllegalAccessException(field.getName() + "不能为空!"); } } } } return true; } /** * 过滤掉字段后,校验剩余对象属性不能为空! * * @param obj * @return * @author DengYang */ public static boolean validFieldWithFilter(Object obj, String... filterField) throws IllegalAccessException { if (obj == null) return false; if (filterField == null || filterField.length < 1) { throw new IllegalAccessException("fieldName参数不能为空!"); } for (Field field : obj.getClass().getDeclaredFields()) { field.setAccessible(true); for (String filter : filterField) { if (field.getName().equals(filter)) continue; if (StringUtils.isEmpty(field.get(obj))) { logger.error("==> " + field.getName() + "不能为空!"); throw new IllegalAccessException("fieldName参数不能为空!"); } } } return true; } public static void main(String[] args) throws Exception { Test user = new Test(); user.setName("阿斯蒂芬"); user.setAge(0); // System.out.println(validField(user)); System.out.println(validFieldWithFilter(user, new String[]{"sdf", "沙发垫"})); } }