我有一个对象,该对象有近 30 个属性,我想从该对象获取所有 null 属性。
现在我通过 if 条件分别为每个属性执行此操作,因此我的代码非常大,java 中是否有任何方法可以从对象获取 null 属性。
请帮忙获取这个。
编辑正在上传我的数据,我想向用户显示空字段作为错误消息。
最佳答案
这是使用反射获取所有空字段的方法:
YourClassObject objectToIntrospect = new YourClassObject();
for (Field field : objectToIntrospect.getClass().getDeclaredFields()) {
field.setAccessible(true); // to allow the access of member attributes
Object attribute = field.get(objectToIntrospect);
if (attribute == null) {
System.out.println(field.getName() + "=" + attribute);
}
}
关于java - 从对象获取 null 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20510555/