4

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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Mohsen
  • 3,512
  • 3
  • 38
  • 66

3 Answers3

2

PropertyUtils has a specific method for nested properties getNestedProperty(...) that handles NPE by throwing a NestedNullException, which is probably(?) better for the eye.

Here is the Javadoc.

2

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 npe){
    return nullreplace;
  }
}

Kind of sucks, but it will work.

Mohsen
  • 3,512
  • 3
  • 38
  • 66
Chad Okere
  • 4,570
  • 1
  • 21
  • 19
  • Well NPE may be thrown for other causes, say bean itself is null. Isn't there any feature in beanutils to handle this? – Mohsen May 02 '10 at 11:36
1

If someone else is searching the answer

    Guia g = new Guia();
    GuiaParticipante gp = new GuiaParticipante(1);
    g.setTbGuiaParticipanteCollection(Collections.singletonList(gp));//comment this line to test
    String name = "tbGuiaParticipanteCollection[0].codParticipante";//the expression itself
    Resolver resolver = new DefaultResolver();//used to "clean" the expression
    if (resolver.isIndexed(name)) {
        String property = resolver.getProperty(name);//remove the [0].codParticipante

        if (PropertyUtils.getProperty(g, property) != null) { //get the collection object, so you can test if is null
            String cod = BeanUtils.getNestedProperty(g, name); //get the value if the collection isn't null
            System.out.println(cod);
        }
    } 
thiago
  • 11
  • 1