访问bean的嵌套/索引属性时如何防止NPE [英] How to prevent NPE when accessing a nested/indexed property of a bean

查看:248
本文介绍了访问bean的嵌套/索引属性时如何防止NPE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用commons-beanutils访问嵌套bean时,有什么方法可以防止NPE吗? 这是我的代码:

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");

在这种情况下,我希望getProperty()要么在human.getParent() == null时返回空字符串("),要么以抛出NPE之外的其他方式处理它.

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.

推荐答案

他们正在考虑

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.

这篇关于访问bean的嵌套/索引属性时如何防止NPE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆