如何避免missingPropertyException [英] how to avoid missingPropertyException
本文介绍了如何避免missingPropertyException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果对象没有属性,我打电话给该属性,我们得到'missingPropertyException'。我可以以类似安全的方式执行类似于缺失属性的操作吗(?),所以它不会通过异常吗?
谢谢
def result = obj
解决方案
.hasProperty('b')? obj.b:null
如果对象没有属性,则返回null ...
另一个方法是像这样为你的课程添加 propertyMissing
:
def propertyMissing(name){
null
}
这意味着任何缺少的属性只会导致null。
If object does not have property and i am calling the property, we got 'missingPropertyException'. Can i do something like safe null (?.) the same way for missing properties so it doesn't through exceptions?
Thank You
解决方案
One option would be:
def result = obj.hasProperty( 'b' ) ? obj.b : null
Which would return null if the object doesn't have the property...
Another would be to add propertyMissing
to your class like so:
def propertyMissing( name ) {
null
}
This means that any missing properties would just result in null.
这篇关于如何避免missingPropertyException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!