count对象的非空数



我正在制作一个方法,可以计算对象的非空值,但我有一个对象在另一个对象内,我必须确认该对象是否为空,我尝试了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...

尽管"result"对象没有值它说它不是空的

Setter

ResultExceptionDTO result = new ResultExceptionDTO();
ExceptionDTO dto = new ExceptionDTO();
dto.setParam("param");
dto.setResult(result);
validChoice(dto, ExceptionDTO.class);

这里不应该显示结果"与null不同,因为到目前为止存在类"ResultExceptionDTO"的实例。与其空属性

下面是有效的方法:

public static long countNullFields(Object o){
return Arrays.stream(o.getClass().getDeclaredFields())
.map(field -> {
try {
field.setAccessible(true);
return field.get(o);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
throw new IllegalArgumentException();
})
.filter(Objects::isNull)
.count();
}

最新更新