How to prevent NPE when accessing a nested/indexed property of a bean
-
02-10-2019 - |
Question
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.
Solution
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.
OTHER TIPS
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.
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);
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow