RubenLaguna
RubenLaguna

Reputation: 24696

Is there a Groovy equivalent to Gradle findProperty?

I'm looking for a way to avoid having to check for the property first with hasProperty().

Ideally I would like to have something like

def a = myobj.getPropertyOrElse("mypropname", "defaultvalueifpropertymissing')

I see that gradle has a findProperty() but I can't find a similar thing for plain groovy.

Upvotes: 0

Views: 696

Answers (3)

jihor
jihor

Reputation: 2599

One can use getProperties() of MetaClass or getProperty() of GroovyObject:

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

Upvotes: 0

tylerwal
tylerwal

Reputation: 1870

The hasProperty method returns a MetaProperty instance that you can use to retrieve the value by passing the original instance:

def a = myobj.hasProperty('mypropname')?.getProperty(myobj) ?: 
    'defaultvalueifpropertymissing'

And then use the Safe navigation operator(?.) and Elvis operator (?:) to avoid the if/else.

Upvotes: 2

RubenLaguna
RubenLaguna

Reputation: 24696

The shortest version I could think of is

def a = if (a.hasProperty("mypropname")) a.getProperty("mypropname") else "defaultvalueifmissing"

which obviously repeats the property name twice. Creating your own method is possible but it's limited to your current class.

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")

Upvotes: 0

Related Questions