Domanda

Esiste un modo per prevenire l'NPE quando si accede a un fagiolo nidificato usando i common-beanutili? Ecco il mio codice:

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

In questo caso voglio getProperty() per restituire la stringa vuota ("") quando human.getParent() == null o gestirlo in un modo altro che lancia un NPE.

È stato utile?

Soluzione

Stavano pensando Aggiunta Caratteristiche linguistiche a JDK7, ma Alla fine non sono stati aggiunti

Per ora dovrai controllare manualmente. Puoi semplicemente hackerarlo e creare una funzione come

public static void propertyHack(Object bean, String property, String nullreplace){
  try{
    return new BeanUtilsBean().getProperty(bean, property);
  }
  catch(NullPointerException npe){
    return nullreplace;
  }
}

Un po 'fa schifo, ma funzionerà.

Altri suggerimenti

PropertyUtils ha un metodo specifico per le proprietà nidificate getNestedProperty(...) che gestisce NPE lanciando un NestedNullException, che è probabilmente (?) MEGLIO per l'occhio.

Ecco il Javadoc.

Se qualcun altro sta cercando la risposta

    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);
        }
    } 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top