有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从对象获取空属性

我在该对象中有一个对象,我有将近30个属性,我想从该对象中获取所有空属性

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

请帮忙拿这个

编辑在上载数据时,我想向用户显示空字段作为错误消息


共 (2) 个答案

  1. # 1 楼答案

    首先,你需要Fields。然后你get the values,然后当值为^{时添加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.
    }
    
  2. # 2 楼答案

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

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