Reputation: 3018
I want to get a property via string like:
PropertyUtils.getNestedProperty(object, propertyName);
For example I have Person object and I want to get the name of the father...
PropertyUtils.getNestedProperty(person, "father.firstName");
Now maybe the person doesn't have a father so the object is null and I get a org.apache.commons.beanutils.NestedNullException.
Is it ok to catch this exception (since it is a runtime exception) or should I first find out if the father is null? Or are there other workarounds?
Upvotes: 0
Views: 2261
Reputation: 11619
If you expect a null
return instead of NestedNullException
if the nested property is null, you can create your own static method that wraps the PropertyUtils.getNestedProperty
and catches NestedNullException
to return null
:
public static Object getNestedPropertyIfExists(Object bean, String name) {
try {
return PropertyUtils.getNestedProperty(bean, name);
} catch (NestedNullException e) {
// Do nothing
}
return null;
}
Upvotes: 3