11

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

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

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

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

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

6 回答 6

9

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

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

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

}
于 2011-03-24T17:11:47.467 回答
1

您可以将 Appache 常用StringUtils.isEmpty()方法与BeanUtils.getProperties().

于 2011-03-24T15:34:01.843 回答
0

嘿,凯文,还没有看到像您要求的方法(我自己也对它感兴趣),但是,您是否考虑过在运行时使用反射来查询您的对象?

于 2011-03-24T15:33:02.080 回答
0

I don't know a library that does this, but using reflection, it is not too hard to implement by yourself. You can easily loop over getter methods of a class and decide whether the instance has a value set, you can further decide the outcome depending on the getter's return type.

The hard part is to define which members of a class you consider being "useful data". Just leaving out Lists, Maps and Arrays probably won't get you far.

I would actually consider writing your own Annotation type in order to "mark" the appropiate "useful" members (which could then be noticed+handled by the reflection code). I don't know if this is an elegant approach to your problem, since I don't know how many classes are affected.

于 2011-03-24T15:44:24.137 回答
0

我真的无法想象整个对象图中完全没有任何内容的东西会进入应用程序的情况。此外,究竟什么会被认为是“空的”?那只是指字符串和集合吗?只有空格的字符串会算吗?那么数字呢......任何数字都会使对象非空,或者像-1这样的特定数字会算作空吗?作为另一个问题,知道对象中是否没有内容通常似乎没有用...通常您需要确保特定字段具有特定数据等。有太多可能性在我看来,一些像这样的一般方法是有意义的。

也许像JSR-303这样更完整的验证系统会更好。其参考实现是Hibernate Validator

于 2011-03-24T15:55:13.340 回答
0

尽管上述实用方法都不是通用的。唯一的方法(据我所知)是与一个空对象进行比较。创建对象的实例(没有设置属性)并使用“.equals”方法进行比较。确保对于 2 个相等的非空对象和 2 个空对象的 true 正确实现 equals。

于 2011-03-24T16:40:58.977 回答