gpt4 book ai didi

java - 如何处理NestedNullException(扩展RuntimeException)

转载 作者:行者123 更新时间:2023-12-01 09:44:56 26 4
gpt4 key购买 nike

我想通过字符串获取属性,例如:

PropertyUtils.getNestedProperty(object, propertyName);

例如,我有 Person 对象,我想获取父亲的名字...

PropertyUtils.getNestedProperty(person, "father.firstName");

现在也许这个人没有父亲,所以该对象为空,我得到一个 org.apache.commons.beanutils.NestedNullException。

是否可以捕获此异常(因为它是运行时异常),或者我应该首先找出父亲是否为空?或者还有其他解决方法吗?

最佳答案

如果您希望在嵌套属性为 null 时返回 null 而不是 NestedNullException,则可以创建自己的静态方法来包装 PropertyUtils.getNestedProperty 并捕获 NestedNullException 以返回 null:

public static Object getNestedPropertyIfExists(Object bean, String name) {
try {
return PropertyUtils.getNestedProperty(bean, name);
} catch (NestedNullException e) {
// Do nothing
}
return null;
}

关于java - 如何处理NestedNullException(扩展RuntimeException),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38142397/

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