Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

groovy: Have a field name, need to set value and don't want to use switch

Tags:

groovy

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.

like image 583
BZ. Avatar asked Sep 04 '11 06:09

BZ.


People also ask

How do I set boolean value in Groovy?

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.

What does def mean in Groovy?

The def keyword is used to define an untyped variable or a function in Groovy, as it is an optionally-typed language.

How do you use assert in if condition in Groovy?

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.


2 Answers

You can use GStrings when you get a field, like this:

def obj = new TestObj()
def fieldToUpdate = 'field1'
obj."$fieldToUpdate" = 3
like image 67
xlson Avatar answered Oct 15 '22 13:10

xlson


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
like image 23
topchef Avatar answered Oct 15 '22 14:10

topchef