ubiquibacon
ubiquibacon

Reputation: 10677

Get variable dynamically

Is there any way to reference variables dynamically like methods? Here is the Groovy example of referencing a method dynamically:

class Dog {
  def bark() { println "woof!" }
  def sit() { println "(sitting)" }
  def jump() { println "boing!" }
}

def doAction( animal, action ) {
  animal."$action"()                  //action name is passed at invocation
}

def rex = new Dog()

doAction( rex, "bark" )               //prints 'woof!'
doAction( rex, "jump" )               //prints 'boing!'

... But doing something like this doesn't work:

class Cat {
    def cat__PurrSound__List = ['a', 'b', 'c']
    def cat__MeowSound__List = [1, 2, 3]

    def someMethod(def sound) {
        assert sound == "PurrSound"

        def catSoundListStr = "cat__${obj.domainClass.name}__List"
        assert catSoundListStr = "cat__PurrSound__List"

        def catSoundList = "$catSoundListStr"
        assert catSoundList == cat__PurrSound__List // fail
    }
}

Upvotes: 1

Views: 2537

Answers (1)

tim_yates
tim_yates

Reputation: 171154

Yeah, so you can do:

def methodName = 'someMethod'
assert foo."$methodName"() == "asdf" // This works

and to get the object by name, you can do (in a Script at least):

// Cannot use `def` in a groovy-script when trying to do this
foo  = new Foo()

def objectName = 'foo'
assert this."$objectName".someMethod() == "asdf"

Upvotes: 3

Related Questions