public class ValidationUtil {
private static final String PIX_GET = "get";
/**
* 根据传入的属性字段名称,以及bean类型,校验对象中的字段值是否存在null
*
* @param object
* @param checkedFieldNames
* @author xiongbangwen
* @date 2021/9/13 15:56
*/
public static void checkFieldExistEmpty(Object object, List<String> checkedFieldNames) {
if (null == object) {
throw new ServiceException("ValidationUtil#checkFieldExistEmpty object param is null");
}
Class<?> clazz = object.getClass();
Field[] fields = clazz.getDeclaredFields();
String fieldName = "";
StringBuilder methodName = null;
Method method = null;
Object result = null;
for (Field field : fields) {
fieldName = field.getName();
if (!hasElement(fieldName, checkedFieldNames)) {
continue;
}
methodName = new StringBuilder(PIX_GET);
// 驼峰式命名,第一个改为大写,后续保持一致。进行getXxx()操作
methodName = methodName.append(fieldName.substring(0, 1).toUpperCase())
.append(fieldName.substring(1));
try {
method = clazz.getDeclaredMethod(methodName.toString());
result = method.invoke(object);
} catch (Exception e) {
e.printStackTrace();
}
if (null == result || "".equals(result)) {
// 存在空属性,抛出异常
throw new ServiceException(fieldName.concat("不能为空"));
}
}
}
/**
* 检测container数组是否包含element元素
*
* @return boolean,true 包含
*/
private static boolean hasElement(String element, List<String> containers) {
return containers.contains(element);
}
Java根据传入的属性字段名称,以及bean类型,校验对象中的字段值是否存在null
最新推荐文章于 2023-08-06 10:38:40 发布