java - 测试空Java对象图的Commons方法?

标签 java spring apache-commons utilities

我发现自己写了一个这样的方法:

boolean isEmpty(MyStruct myStruct) {
  return (myStruct.getStringA() == null || myStruct.getStringA().isEmpty())
    && (myStruct.getListB() == null || myStruct.getListB().isEmpty());
}

然后想象这个结构有很多其他属性和其他嵌套列表,你可以想象这个方法变得非常大并且与数据模型紧密耦合。

Apache Commons、Spring 或其他 FOSS 实用程序是否有能力以递归方式反射性地遍历对象图并确定它基本上没有任何有用的数据,除了列表、数组、 map 等的持有者?这样我就可以写了:

boolean isEmpty(MyStruct myStruct) {
  return MagicUtility.isObjectEmpty(myStruct);
}

最佳答案

感谢 Vladimir 为我指明了正确的方向(我给了你一个赞成票!)尽管我的解决方案使用 PropertyUtils 而不是 BeanUtils

我确实必须实现它,但这并不难。这是解决方案。我只为字符串和列表做这件事,因为这就是我目前所拥有的。可以为 Maps 和 Arrays 扩展。

import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;

public class ObjectUtils {

  /**
   * Tests an object for logical emptiness. An object is considered logically empty if its public gettable property
   * values are all either null, empty Strings or Strings with just whitespace, or lists that are either empty or
   * contain only other logically empty objects.  Currently does not handle Maps or Arrays, just Lists.
   * 
   * @param object
   *          the Object to test
   * @return whether object is logically empty
   * 
   * @author Kevin Pauli
   */
  @SuppressWarnings("unchecked")
  public static boolean isObjectEmpty(Object object) {

    // null
    if (object == null) {
      return true;
    }

    // String
    else if (object instanceof String) {
      return StringUtils.isEmpty(StringUtils.trim((String) object));
    }

    // List
    else if (object instanceof List) {
      boolean allEntriesStillEmpty = true;
      final Iterator<Object> iter = ((List) object).iterator();
      while (allEntriesStillEmpty && iter.hasNext()) {
        final Object listEntry = iter.next();
        allEntriesStillEmpty = isObjectEmpty(listEntry);
      }
      return allEntriesStillEmpty;
    }

    // arbitrary Object
    else {
      try {
        boolean allPropertiesStillEmpty = true;
        final Map<String, Object> properties = PropertyUtils.describe(object);
        final Iterator<Entry<String, Object>> iter = properties.entrySet().iterator();
        while (allPropertiesStillEmpty && iter.hasNext()) {
          final Entry<String, Object> entry = iter.next();
          final String key = entry.getKey();
          final Object value = entry.getValue();

          // ignore the getClass() property
          if ("class".equals(key))
            continue;

          allPropertiesStillEmpty = isObjectEmpty(value);
        }
        return allPropertiesStillEmpty;
      } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
      } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
      } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
      }
    }
  }

}

关于java - 测试空Java对象图的Commons方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5421570/

相关文章:

java - 如何将 Jasypt 与 Spring Autowiring 一起使用?

java - 无法使用 Spring 创建 java.util.concurrent.ThreadPoolExecutor 的 bean

java - 读取 clob 对象时 Spring jdbc 模板连接关闭异常

java - 在 EditText 中检测键盘的关闭(通过后退按钮)

java - 为什么Optional isPresent类方法采用Consumer<? super T> 作为参数,而不是 Consumer<T>?

java 替换全部()

java - 使用 Apache Commons compress 创建 gzip 存档

Java 日期转换 - UTC 到本地 - 工作方式因时区而异

java - 使用 Thymeleaf 和 Spring Boot 转换器列出 JSON 字符串

java - 如何使用 DurationFormatUtils 类获得所需格式的结果?