I have an object with several fields,
class TestObj {
def field1
def field2
}
I have a pair of values v1="field1" and v2="value2" I would like to set v2 into the appropriate field based on the name of v1, but I'd prefer not to have to do it with a switch or if statements, I keep thinking there has to be a much "groovier" way of achieving the result other than doing something li开发者_开发百科ke this:
setValues(def fieldName, def fieldVal) {
if (fieldName.equals("field1")) {
field1 = fieldVal
}
if (fieldName.equals("field2")) {
field2 = fieldVal
}
}
I've tried doing this:
setValues(def fieldName, def fieldVal) {
this['${fieldName}'] = fieldVal
}
However that fails, saying there's no property ${fieldName}
Thanks.
You can use GStrings when you get a field, like this:
def obj = new TestObj()
def fieldToUpdate = 'field1'
obj."$fieldToUpdate" = 3
In Groovy you don't have to define a property to have a property. Use getProperty
and setProperty
called property access hooks in Groovy:
class TestObj {
def properties = [:]
def getProperty(String name) { properties[name] }
void setProperty(String name, value) { properties[name] = value }
void setValues(def fieldName, def fieldVal) {setProperty(fieldName, fieldVal)}
}
def test = new TestObj()
test.anyField = "anyValue"
println test.anyField
test.setValues("field1", "someValue")
println test.field1
test.setValues("field2", "anotherValue")
println test.field2
精彩评论