我发现自己编写了一个这样的方法:
boolean isEmpty(MyStruct myStruct) {
return (myStruct.getStringA() == null || myStruct.getStringA().isEmpty())
&& (myStruct.getListB() == null || myStruct.getListB().isEmpty());
}然后想象这个具有许多其他属性和其他嵌套列表的结构,您可以想象这个方法变得非常大,并且与数据模型紧密耦合。
Apache Commons、Spring或其他一些自由/开源软件实用程序是否能够递归地反射遍历对象图,并确定除了列表、数组、映射等的持有者之外,它基本上没有任何有用的数据?这样我就可以写下:
boolean isEmpty(MyStruct myStruct) {
return MagicUtility.isObjectEmpty(myStruct);
}发布于 2011-03-25 01:11:47
感谢Vladimir为我指明了正确的方向(我给了你一张赞成票!)尽管我的解决方案使用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-24 23:34:02
您可以将Appache Common StringUtils.isEmpty()方法与BeanUtils.getProperties()结合使用。
发布于 2011-03-24 23:33:02
嘿,凯文,还没有看到任何像你要求的方法(我自己也很感兴趣),然而,你考虑过在运行时使用反射来查询你的对象吗?
https://stackoverflow.com/questions/5421570
复制相似问题