参考文章
在参考文章的基础上,完善了检查父类字段功能。
public class ValidationUtil {
private static final String PIX_GET = "get";
public static Result checkFieldExistEmpty(Object object, List<String> checkedFields, List<String> checkedFieldsName) {
if (null == object) {
throw new ServiceException("ValidationUtil#checkFieldExistEmpty object param is null");
}
Class<?> aClass = object.getClass();
List<Field> fieldList = new ArrayList(Arrays.asList(aClass.getDeclaredFields()));
fieldList.addAll(Arrays.asList(aClass.getSuperclass().getDeclaredFields()));
String fieldName = "";
StringBuilder methodName = null;
Method method = null;
Object result = null;
for (Field field : fieldList) {
fieldName = field.getName();
if (!hasElement(fieldName, checkedFields)) {
continue;
}
methodName = new StringBuilder(PIX_GET);
methodName = methodName.append(fieldName.substring(0, 1).toUpperCase())
.append(fieldName.substring(1));
try {
method = aClass.getDeclaredMethod(methodName.toString());
} catch (NoSuchMethodException e) {
try {
method = aClass.getSuperclass().getDeclaredMethod(methodName.toString());
} catch (NoSuchMethodException ex) {
return Result.failed("未找到该字段信息,请检查数据是否正确。");
}
} finally {
try {
result = method.invoke(object);
} catch (Exception e) {
e.printStackTrace();
}
}
if (null == result || "".equals(result)) {
int i = checkedFields.indexOf(fieldName);
return Result.failed(checkedFieldsName.get(i).concat("不能为空,请完善后重新提交申请。"));
}
}
return Result.succeed("ok");
}
private static boolean hasElement(String element, List<String> containers) {
return containers.contains(element);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)