访问豆的嵌套/索引属性时如何防止NPE
-
02-10-2019 - |
题
有什么方法可以防止使用Commons-Beanutils进入嵌套豆时NPE?这是我的代码:
new BeanUtilsBean().getProperty(human, "parent.name");
在这种情况下,我想要 getProperty()
要么返回空字符串(“”) human.getParent() == null
或以其他方式处理NPE。
其他提示
PropertyUtils
具有嵌套特性的特定方法 getNestedProperty(...)
通过扔一个来处理NPE NestedNullException
, ,哪个可能(?)对眼睛更好。
这里是 Javadoc.
如果其他人在搜索答案
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);
}
}
不隶属于 StackOverflow