我正在寻找一种方法来避免首先使用hasProperty()
检查属性。
理想情况下,我想要像
这样的东西def a = myobj.getPropertyOrElse("mypropname", "defaultvalueifpropertymissing')
我看到gradle有一个findProperty()
,但我找不到类似于普通常规的东西。
答案 0 :(得分:2)
hasProperty
方法返回一个MetaProperty
实例,您可以通过传递原始实例来检索该值:
def a = myobj.hasProperty('mypropname')?.getProperty(myobj) ?:
'defaultvalueifpropertymissing'
然后使用安全导航操作符(?.
)和Elvis操作符(?:
)来避免if/else
。
答案 1 :(得分:0)
我能想到的最短版本是
def a = if (a.hasProperty("mypropname")) a.getProperty("mypropname") else "defaultvalueifmissing"
显然重复了两次属性名称。可以创建自己的方法,但它仅限于您当前的类。
class MyClass {
String name = "the name"
}
def a = new MyClass()
def getProperty(Object theInstance, String propName, Object defaultValue) {
if (theInstance.hasProperty(propName)) theInstance.getProperty(propName) else defaultValue
}
assert "the name" == getProperty(a, "name", "")
assert "default value" == getProperty(a, "method", "default value")
答案 2 :(得分:0)
可以使用MetaClass的getProperties()
或GroovyObject的getProperty()
:
class Test {
String field1
String field2
}
def test = new Test(field1: "value1", field2: null)
// using MetaClass.getProperties()
println test.properties["field1"] // value1
println test.properties["field2"] // null
println "field2" in test.properties.keySet() // true
println test.properties["field3"] // null
println "field3" in test.properties.keySet() // false
// using GroovyObject.getProperty()
println test.getProperty("field1") // value1
println test.getProperty("field2") // null
println test.getProperty("field3") // groovy.lang.MissingPropertyException