访问bean的嵌套/索引属性时如何防止NPE

编程入门 行业动态 更新时间:2024-10-23 15:29:07
本文介绍了访问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.

推荐答案

他们正在考虑向JDK7添加了语言功能,但最终未添加它们

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

本文发布于:2023-10-31 06:00:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545221.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   索引   属性   如何防止   bean

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!