如何避免 MissingPropertyException [英] How to avoid MissingPropertyException

查看:41
本文介绍了如何避免 MissingPropertyException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个对象没有属性并且我正在访问该属性,我们会得到一个 MissingPropertyException.我可以做一些类似于安全 null (?.) 的事情来防止丢失的属性,这样它就不会抛出异常吗?

If an object does not have a property and I am accessing the property, we get a MissingPropertyException. Can I do something similar to safe null (?.) to guard against missing properties so it doesn't throw an exception?

推荐答案

一种选择是:

def result = obj.hasProperty( 'b' ) ? obj.b : null

如果对象没有属性,哪个将返回 null...

Which would return null if the object doesn't have the property...

另一种方法是将 propertyMissing 添加到您的类中,如下所示:

Another would be to add propertyMissing to your class like so:

def propertyMissing( name ) {
  null
}

这意味着任何缺失的属性都会导致 null.

This means that any missing properties would just result in null.

这篇关于如何避免 MissingPropertyException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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