How to prevent NPE when accessing a nested / indexed bean property

Is there a 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 to getProperty()return an empty string ("") at human.getParent() == nullor handle it in another way that threw NPE.

+3
source share
3 answers

They thought about adding language features to JDK7, but they were not ultimately added.

Now you 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.

+2
source

PropertyUtils getNestedProperty(...), NPE, NestedNullException, , , (?) .

Javadoc.

+1

If someone is looking for an 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);
        }
    } 
0
source

Source: https://habr.com/ru/post/1743695/


All Articles