从对象获取null属性

时间:2013-12-11 04:31:36

标签: java

我有一个对象,该对象有近30个属性,我想从对象获取所有null属性。

现在我正在通过if分别为每个属性设置条件,因此我的代码非常大,在java中有任何方法可以从对象获取null属性。

请帮忙搞定。

编辑上传我的数据我想向用户显示空字段作为错误消息。

2 个答案:

答案 0 :(得分:4)

这是使用反射获取所有空字段的方法:

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

答案 1 :(得分:3)

首先,您需要Fields。然后是get the values,然后在值为null时添加field name。所以,像这样 -

public static String[] getNullFields(Object obj) {
  List<String> al = new ArrayList<String>();
  if (obj != null) {              // Check for null input.
    Class<?> cls = obj.getClass();
    Field[] fields = cls.getFields();
    for (Field f : fields) {
      try {
        if (f.get(obj) == null) { // Check for null value.
          al.add(f.getName());    // Add the field name.
        }
      } catch (IllegalArgumentException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      }
    }
  }
  String[] ret = new String[al.size()]; // Create a String[] to return.
  return al.toArray(ret);               // return as an Array.
}
相关问题