0

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?

ave4496
  • 2,950
  • 3
  • 21
  • 48
  • 1
    For a nested property, it is always good to validate whether the parent property fetched is null and then proceed to fetch the child – Amal Gupta Jul 01 '16 at 09:59
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Raedwald Jul 01 '16 at 11:40

1 Answers1

3

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;
}
Wilson
  • 11,339
  • 2
  • 29
  • 33
  • Yeah apache should add this or add param _allowNull_ to the get property functions. Also problematic with _BeanComparator_ and _ComparableComparator_ all ignoring the facts that values can be _null_. We had to create our own classes for those cases. – djmj Aug 09 '22 at 12:52