知道Class中的所有变量是否为空的最佳方法是什么?

这意味着该类已初始化,但未设置变量。

样本类:

public class User { String id = null; String name = null; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } 

实际的类是巨大的,我不想检查每个变量是否(xyz == null)。

尝试这样的事情:

 public boolean checkNull() throws IllegalAccessException { for (Field f : getClass().getDeclaredFields()) if (f.get(this) != null) return false; return true; } 

虽然如果可行的话,检查每个变量可能会更好。

另一个针对Java 8的非reflection解决方案,在paxdiabo的答案中,但没有使用一系列if ,将流式传输所有字段并检查空值:

 return Stream.of(id, name) .allMatch(Objects::isNull); 

这仍然很容易保持,同时避免reflection

“最佳”是这样一个主观词:-)

我只想使用检查每个变量的方法。 如果你的class级已经有很多这样的话,如果你做了类似的事情,那么规模的增加就不会那么多了:

 public Boolean anyUnset() { if ( id == null) return true; if (name == null) return true; return false; } 

如果您按照相同的顺序保存所有内容,则代码更改(如果您是偏执狂,则使用脚本自动检查)将相对轻松。

或者(假设它们都是字符串),您基本上可以将这些值放入某种类型的映射(例如, HashMap )中,并保留该列表的键名列表。 这样,您可以遍历键列表,检查值是否设置正确。

它也可以在不使用reflection的情况下完成。

解决方案是动态的。 使用新字段扩展类时,无需将它们添加到列表中或添加其他空检查。

注意:

我使用了Lombok的EqualsAndHashCode注释。

您必须确保默认构造函数不是使用自定义行为实现的,并且您的字段没有内置java默认值以外的默认值(引用类型为null,int为0,等等)。

 @EqualsAndHashCode public class User { private static User EMPTY = new User(); private String id = null; private String name = null; private User() { } public User(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isEmpty() { return this.equals(EMPTY); } } 
 Field[] field = model.getClass().getDeclaredFields(); for(int j=0 ; j 

在我看来,最好的方式是反思,正如其他人所推荐的那样。 这是一个评估每个本地字段为null的示例。 如果找到一个非null,则method将返回false。

 public class User { String id = null; String name = null; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } 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; } public static void main(String args[]) { System.out.println(new User().allNull()); } } 

溪流怎么样?

 public boolean checkFieldsIsNull(Object instance, List fieldNames) { return fieldNames.stream().allMatch(field -> { try { return Objects.isNull(instance.getClass().getDeclaredField(field).get(instance)); } catch (IllegalAccessException | NoSuchFieldException e) { return true;//You can throw RuntimeException if need. } }); }