如何查找 DTO 中是否至少有一个字段为空

How to find if at least one field is null in a DTO

我使用 Spring-Batch 处理一个 Batch。 在处理器中,我必须处理大约有二十个字段的 DTO。

功能上,如果没有字段是空的,我就无事可做。 所以我想首先找出是否没有字段为空。

但我真的不想用二十

做一个 "if"
DTO.getValue1 != null && DTO.getValue2 != null [...]

我想知道是否有更简洁的方法来做到这一点?

提前致谢。

您可以使用反射进行验证。在 DTO 中定义一个 isNull 方法来检查空字段。

public boolean isNull() {
        Field fields[] = this.getClass().getDeclaredFields();
        for (Field f : fields) {
            try {
                Object value = f.get(this);
                if (value != null) {
                    return false;
                }
            }
            catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        }
        return true;

    }