Cómo evitar NPE al acceder a una propiedad anidada/indexada de un frijol
-
02-10-2019 - |
Pregunta
¿Hay alguna forma de evitar NPE cuando se accede a un frijol anidado con productos comunes? Aquí está mi código:
new BeanUtilsBean().getProperty(human, "parent.name");
En este caso quiero getProperty()
para devolver la cadena vacía ("") cuando human.getParent() == null
o manejarlo de una manera que tire de un NPE.
Solución
Estaban pensando en suplente Características del idioma para JDK7, pero finalmente no fueron agregados
Por ahora tendrás que verificar manualmente. Puedes simplemente hackearlo y crear una función como
public static void propertyHack(Object bean, String property, String nullreplace){
try{
return new BeanUtilsBean().getProperty(bean, property);
}
catch(NullPointerException npe){
return nullreplace;
}
}
Es un poco apestoso, pero funcionará.
Otros consejos
PropertyUtils
tiene un método específico para propiedades anidadas getNestedProperty(...)
que maneja NPE lanzando un NestedNullException
, que probablemente sea (?) Mejor para el ojo.
Aquí está el Javadoc.
Si alguien más está buscando la respuesta
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);
}
}