views:

58

answers:

2

Is there any way to prevent NPE when accessing a nested bean using commons-beanutils? Here is my code:

new BeanUtilsBean().getProperty(human, "parent.name");

In this case I want getProperty() to either return empty string ("") when human.getParent() == null or handle it in a way other that throwing an NPE.

+1  A: 

They were thinking of adding language features to JDK7, but ultimately they weren't added

For now you'll have to manually check. You can just hack it and create a function like

public static void propertyHack(Object bean, String property, String nullreplace){
  try{
    return new BeanUtilsBean().getProperty(bean, property);
  }
  Catch(NullpointerException ne){
    return nullreplace;
  }
}

Kind of sucks, but it will work.

Chad Okere
Well NPE may be thrown for other causes, say bean itself is null. Isn't there any feature in beanutils to handle this?
Mohsen
A: 

commons-beanutil is open source software. If you want to know exactly what features it has, and you don't believe what other people are telling you here, you should read the source.

bmargulies
I've found your answer unduly harsh. That's not a matter of believing what others tell. You can see in my comment that there may be an issue in the suggested hack (although I used to use this before in my code, anyways). I first checked commons-beanutils source code and then asked my question here. So if you think this feature is missing in the library, just help by commenting on the above answer that "it's currently missing".Thanks!
Mohsen
You are entitled to your opinion. I could not have left that comment, because I have never read the source of commons-beanutil.
bmargulies