如何处理NestedNullException(扩展RuntimeException)

时间:2016-07-01 09:55:38

标签: java

我希望通过字符串获取属性,如:

PropertyUtils.getNestedProperty(object, propertyName);

例如我有Person对象,我想得到父亲的名字......

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

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

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

1 个答案:

答案 0 :(得分:1)

如果嵌套属性为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;
}