我使用 Spring-Batch 处理 Batch。 在处理器中,我必须处理大约有 20 个字段的 DTO。
从功能上来说,如果没有字段为空,我就无事可做。 所以我想首先找出是否没有字段为空。
但我真的不想用二十来做“如果”
DTO.getValue1 != null && DTO.getValue2 != null [...]
我想知道是否没有更干净的方法来做到这一点?
提前致谢。
最佳答案
您可以使用反射来进行验证。在 DTO 中定义 isNull 方法来检查 null 字段。
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;
}
关于java - 如何查找 DTO 中是否至少有一个字段为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57809219/