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 に答える