Groovy:如何测试属性访问是否成功? [英] Groovy: how to test if a property access will be successful?
本文介绍了Groovy:如何测试属性访问是否成功?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个变量Object foo,它不为null.我想使用foo.bar,但前提是它不会以没有这样的属性:针对类的酒吧:无论如何"轰炸我.
I have a variable Object foo, which is not null. I want to use foo.bar, but only if it won't bomb me with 'No such property: bar for class: Whatever'.
我应该如何进行以下测试:
How should I do the following test:
if (/*test-here*/) {
use(foo.bar)
}
推荐答案
使用object.hasProperty(propertyName)
.如果属性存在,这将返回真实值(属性引用). object.metaClass.hasProperty(instance, propertyName)
也是可能的.使用object.respondsTo(methodName)
测试方法是否存在.
Use object.hasProperty(propertyName)
. This will return a truthy value (the property reference) if the property exists. Also object.metaClass.hasProperty(instance, propertyName)
is possible. Use object.respondsTo(methodName)
to test for method existence.
这篇关于Groovy:如何测试属性访问是否成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文