gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:50:01 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com