So verhindern Sie NPE, wenn Sie auf eine verschachtelte/indizierte Eigenschaft einer Bohne zugreifen
-
02-10-2019 - |
Frage
Gibt es eine Möglichkeit, NPE beim Zugriff auf eine verschachtelte Bohne mit Commons-Beanutils zu verhindern? Hier ist mein Code:
new BeanUtilsBean().getProperty(human, "parent.name");
In diesem Fall will ich getProperty()
um entweder leere Zeichenfolge zurückzugeben (""), wenn human.getParent() == null
Oder handeln Sie es auf andere Weise, die ein NPE werfen.
Lösung
Sie dachten an Hinzufügen Sprachmerkmale zu JDK7, aber aber Letztendlich wurden sie nicht hinzugefügt
Im Moment müssen Sie manuell überprüfen. Sie können es einfach hacken und eine Funktion erstellen wie
public static void propertyHack(Object bean, String property, String nullreplace){
try{
return new BeanUtilsBean().getProperty(bean, property);
}
catch(NullPointerException npe){
return nullreplace;
}
}
Irgendwie scheiße, aber es wird funktionieren.
Andere Tipps
PropertyUtils
hat eine spezifische Methode für verschachtelte Eigenschaften getNestedProperty(...)
Das geht mit NPE durch, indem er a wirft NestedNullException
, was ist wahrscheinlich (?) Für das Auge besser.
Hier ist der Javadoc.
Wenn jemand anderes die Antwort sucht
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);
}
}