1

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
    }
}
4
  • assert foo."$someMethod"() == "asdf" won't work, as you don't have a var called someMethod Commented Sep 3, 2013 at 14:20
  • @tim_yates Seems to work fine in my Grails test. I used it like the example here that uses $action. Commented Sep 3, 2013 at 15:15
  • What is driving to use "$foo" instead of foo? Commented Sep 3, 2013 at 15:21
  • @dmahapatro Sorry, I botched the question. As tim_yates said it doesn't work as advertised. I will corrected it. To be clear all I wanted to do was access a variable in a service based on a string that equaled that variables name. Commented Sep 3, 2013 at 16:00

1 Answer 1

3

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"
Sign up to request clarification or add additional context in comments.

6 Comments

Awesome. Works in Grails too.
@dmahapatro What are you running it in? It very much depends on the context, as to whether the object will be found in this
Same way OP has asked. This time I saved the script say BarScript.groovy. Here
@dmahapatro Oh yeah, because this is a Script, you have to remove the def from def foo = new Foo() to get it to work in a Script. Sorry about that...
Correct, its tricky, negligence prone (for me at least). But I still do not understand the rationale behind using "$foo" instead of using foo directly. Asked OP about it. :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.