【问题标题】:count non-null numbers of an object计算对象的非空数
【发布时间】: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 &gt; 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


【解决方案1】:

下面是有效的方法:

    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();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 2021-09-18
    • 2014-07-27
    • 2018-06-27
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多