有什么方法可以防止使用Commons-Beanutils进入嵌套豆时NPE?这是我的代码:

new BeanUtilsBean().getProperty(human, "parent.name");

在这种情况下,我想要 getProperty() 要么返回空字符串(“”) human.getParent() == null 或以其他方式处理NPE。

有帮助吗?

解决方案

他们在想 添加 JDK7的语言功能,但是 最终他们没有添加

现在,您必须手动检查。您可以将其入侵并创建一个函数

public static void propertyHack(Object bean, String property, String nullreplace){
  try{
    return new BeanUtilsBean().getProperty(bean, property);
  }
  catch(NullPointerException npe){
    return nullreplace;
  }
}

有点糟糕,但它会起作用。

其他提示

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);
        }
    } 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top