【发布时间】:2021-10-14 02:38:05
【问题描述】:
我正在制作一个可以计算对象的非空值的方法,但我在另一个对象中有一个对象,我必须确认该对象是否也为空,我尝试使用 isEmpty, isNull 但它说它不是空。
对象
public class ExceptionDTO {
private ResultExceptionDTO result;
private String param;
private String content;
}
验证方法
public static <T> void validChoice(Object request, Class<T> clazz) throws Exception {
int nonNullCount = 0;
for (Field field : clazz.getDeclaredFields())
{
field.setAccessible(true);
if (field.get(request) != null || !ObjectUtils.isEmpty(field.get(request)))
{
System.out.println(field.get(request));
nonNullCount++;
}
}
if (nonNullCount != 1) {
throw new ValidationException(ERROR_MISSING_PARAMS);
}
}
我也试过!ObjectUtils.isNull...
即使“结果”对象没有值,它也表示它不是空的`
二传手
ResultExceptionDTO result = new ResultExceptionDTO();
ExceptionDTO dto = new ExceptionDTO();
dto.setParam("param");
dto.setResult(result);
validChoice(dto, ExceptionDTO.class);
这里不应该向我显示“结果”与 null 不同,因为到目前为止存在具有 null 属性的类“ResultExceptionDTO”的实例
【问题讨论】:
-
当
validChoice查看result的值时,它将看到一个非空值。 Null 是您检查的所有内容。 -
我尝试了 !.isEmpty,但它也没有检查它。
-
isEmpty属于哪一类?ExceptionDTO似乎没有使用该方法实现任何接口。 -
连续三次重复像
field.get(request)这样的表达式对于每个开发人员来说都应该是错误的。这就是局部变量的用途。此外,由于您只是从零开始递增nonNullCount,因此表达式nonNullCount > 1 || nonNullCount == 0等价于简单的nonNullCount != 1。如果这是您的意图,请使用它。如果没有,您必须重新考虑您的程序逻辑,因为这就是您最终要测试的内容。而如果要测试某物是否“空”,则必须先定义“空”的含义。看来,ObjectUtils有不同的定义。 -
进一步注意,您可以避免为每个字段调用
setAccessible(true),使用Field[] array = clazz.getDeclaredFields(); AccessibleObject.setAccessible(array, true); for(Field field: array) { /* your loop body without setAccessible(true); */ }
标签: java spring spring-boot java-8