访问 bean 的嵌套/索引属性时如何防止 NPE
使用 commons-beanutils 访问嵌套 bean 时,有什么方法可以防止 NPE 吗? 这是我的代码:
new BeanUtilsBean().getProperty(human, "parent.name");
在这种情况下,我希望 getProperty()
当 human.getParent() == null
时返回空字符串 ("") 或在除了抛出 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");
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
他们正在考虑添加语言功能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
Kind of sucks, but it will work.
PropertyUtils
有一个用于嵌套属性getNestedProperty(...)
的特定方法,它通过抛出NestedNullException
来处理 NPE,这可能(?)更好为了眼睛。这是 Javadoc。
PropertyUtils
has a specific method for nested propertiesgetNestedProperty(...)
that handles NPE by throwing aNestedNullException
, which is probably(?) better for the eye.Here is the Javadoc.
如果其他人正在寻找答案
If someone else is searching the answer