当使用commons-beanutils访问嵌套bean时,有什么方法可以防止NPE? 这里是我的代码:如何在访问bean的嵌套/索引属性时防止NPE
new BeanUtilsBean().getProperty(human, "parent.name");
在这种情况下,我想getProperty()
要么返回空字符串(“”)时human.getParent() == null
或其他随便丢的NPE的方式处理它。
当使用commons-beanutils访问嵌套bean时,有什么方法可以防止NPE? 这里是我的代码:如何在访问bean的嵌套/索引属性时防止NPE
new BeanUtilsBean().getProperty(human, "parent.name");
在这种情况下,我想getProperty()
要么返回空字符串(“”)时human.getParent() == null
或其他随便丢的NPE的方式处理它。
他们想的adding语言功能JDK7,但ultimately they weren't added
现在你必须手动检查。你可以只砍它,并创建一个像
public static void propertyHack(Object bean, String property, String nullreplace){
try{
return new BeanUtilsBean().getProperty(bean, property);
}
catch(NullPointerException npe){
return nullreplace;
}
}
类吸功能,但它会奏效。
PropertyUtils
有一个嵌套属性的具体方法getNestedProperty(...)
通过抛出NestedNullException
来处理NPE,这对于眼睛来说可能更好(?)。
这是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);
}
}
好NPE,可能会引发其他原因,比如绿豆本身是空的。 beanutils中没有任何功能可以处理这个问题吗? – Mohsen 2010-05-02 11:36:39