Comment éviter NPE lors de l'accès d'une propriété imbriquée / indexé d'un haricot
-
02-10-2019 - |
Question
Y at-il moyen d'éviter NPE lors de l'accès d'un haricot imbriquée à l'aide commons-BeanUtils? Voici mon code:
new BeanUtilsBean().getProperty(human, "parent.name");
Dans ce cas, je veux getProperty()
soit retour chaîne vide ( « ») lorsque human.getParent() == null
ou de le manipuler d'une manière autre que jeter un NPE.
La solution
Ils songeaient ajouter la langue dispose de JDK7, mais finalement, ils ne sont pas ajoutés
Pour l'instant, vous devrez vérifier manuellement. Vous pouvez simplement pirater et créer une fonction comme
public static void propertyHack(Object bean, String property, String nullreplace){
try{
return new BeanUtilsBean().getProperty(bean, property);
}
catch(NullPointerException npe){
return nullreplace;
}
}
Type de succions, mais il fonctionnera.
Autres conseils
PropertyUtils
a une méthode spécifique pour les propriétés imbriquées getNestedProperty(...)
qui gère les NPE en jetant un NestedNullException
, ce qui est probablement (?) Mieux pour l'œil.
Voici le Javadoc .
Si quelqu'un d'autre est à la recherche de la réponse
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);
}
}