本文共 3559 字,大约阅读时间需要 11 分钟。
在软件开发过程中,字段校验是保证程序健壮性和稳定性的重要环节。本文将介绍两种字段校验的常用方法,并展示一种基于工具类的字段校验实现。
在Spring或其他框架中,开发者通常会利用Assert方法进行字段校验。以下是两个典型的校验示例:
Assert.notNull(payable, "Payable不能为空!");Assert.notNull(payable.getNettingStatus(), "Payable.nettingStatus不能为空!");
上述代码使用了Spring的Assert.notNull方法,用于校验对象和对象的特定属性是否为空。这种方法简单直观,适用于字段较少的情况。
在实际项目中,字段数量可能会增加,手动校验每个字段会变得繁琐。为解决这一问题,我们可以编写自定义工具类来实现自动化校验。
以下是我们自定义的ObjectUtils工具类:
public class ObjectUtils { private static final Logger logger = LoggerFactory.getLogger(ObjectUtils.class); 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; } 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; } 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("字段 " + field.getName() + " 不能为空!"); } } } return true; } public static void main(String[] args) throws Exception { Test user = new Test(); user.setName("阿斯蒂芬"); user.setAge(0); // 测试validField方法 System.out.println("字段校验结果:" + validField(user)); // 测试validFieldWithFilter方法 System.out.println("过滤校验结果:" + validFieldWithFilter(user, new String[]{"sdf", "沙发垫"})); }} validField方法
validFieldByFileldName方法
validFieldWithFilter方法
在开发ObjectUtils工具类时,我们主要考虑了以下几点:
setAccessible方法确保反射操作高效。字段校验是保证程序健壮性的重要环节。通过使用现有的框架工具或自定义工具类,我们可以简化校验逻辑,提高开发效率。在实际项目中,可以根据具体需求选择合适的校验方法,并通过工具类进行统一管理。
转载地址:http://wdhfk.baihongyu.com/