1

有没有办法像方法一样动态引用变量? 下面是动态引用方法的 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
    }
}
4

1 回答 1

3

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

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"
于 2013-09-03T14:19:38.440 回答