java Gets the field instance code in the object that is null

  • 2021-07-16 02:34:44
  • OfStack

The following simple code is to share the field of null in java acquisition object. The specific code is as follows:


private static String[] getNullPropertyNames(Object source) {
    final BeanWrapper src = new BeanWrapperImpl(source);
    java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

    Set<String> emptyNames = new HashSet<>();
    for(java.beans.PropertyDescriptor pd : pds) {
      Object srcValue = src.getPropertyValue(pd.getName());
      if (srcValue == null) emptyNames.add(pd.getName());
    }
    String[] result = new String[emptyNames.size()];
    return emptyNames.toArray(result);
  }

PS: Gets the attribute value of null in Java object to

Needless to say, directly paste the code, here you can check the parameters of json object, find the parameters that are not empty, or all the attributes of the object are not empty, which may be much more convenient.


public static List<String> getValue(Object object,List<String> list){
  Field[] field = object.getClass().getDeclaredFields();
  for(int j=0 ; j<field.length ; j++){
    String name = field[j].getName();
    name = name.substring(0,1).toUpperCase()+name.substring(1);
    String type = field[j].getGenericType().toString();
      Method m;
      Object value;
      try {
        m = object.getClass().getMethod("get"+name);
        value = m.invoke(object);
        if(value == null || "".equals(value)){
          list.add(name);
        }
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (IllegalArgumentException e) {
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        e.printStackTrace();
      } catch (NoSuchMethodException e) {
        e.printStackTrace();
      } catch (SecurityException e) {
        e.printStackTrace();
      }
  }
  return list;
}

Summarize

The above is the site to introduce the java Object for null field example code, I hope to help you, if you have any questions welcome to leave me a message, this site will reply to you in time!


Related articles: