是否有一个Groovy等效于Gradle findProperty?

时间:2017-12-11 12:36:10

标签: groovy

我正在寻找一种方法来避免首先使用hasProperty()检查属性。

理想情况下,我想要像

这样的东西
def a = myobj.getPropertyOrElse("mypropname", "defaultvalueifpropertymissing')

我看到gradle有一个findProperty(),但我找不到类似于普通常规的东西。

3 个答案:

答案 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)

可以使用MetaClassgetProperties()GroovyObjectgetProperty()

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