动态获取变量

时间:2013-09-03 14:16:05

标签: dynamic groovy

有没有办法像方法一样动态引用变量? Here是动态引用方法的Groovy示例:

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!'

......但是做这样的事情是行不通的:

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
    }
}

1 个答案:

答案 0 :(得分:2)

是的,所以你可以这样做:

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

并且要按名称获取对象,您可以(至少在脚本中):

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

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