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 like 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.
The groovy string method toBoolean() converts the string value to a boolean value. The toBoolean() documentation says: If the trimmed string is "true", "y" or "1" (ignoring case) then the result is true otherwise it is false.
The def keyword is used to define an untyped variable or a function in Groovy, as it is an optionally-typed language.
The if's condition needs to be an expression. Assertions are for cases where you want it to fail loudly if what you're asserting is not true. Don't use assert unless you want it to throw an exception if the condition is not met.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With