Dynamic 动态获取变量
有没有办法像方法一样动态引用变量?是动态引用方法的Groovy示例:Dynamic 动态获取变量,dynamic,groovy,Dynamic,Groovy,有没有办法像方法一样动态引用变量?是动态引用方法的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
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
}
}
是的,所以你可以:
def methodName = 'someMethod'
assert foo."$methodName"() == "asdf" // This works
要按名称获取对象,您可以(至少在脚本中)执行以下操作:
assert foo.“$someMethod”(==“asdf”
将不起作用,因为您没有名为someMethod
@tim_-yates的变量在我的Grails测试中似乎工作得很好。我像使用$action
的示例一样使用它。是什么驱使我使用“$foo”
而不是foo
?@dmahapatro抱歉,我把问题搞糟了。正如tim_yates所说,它并不像广告宣传的那样有效。我会改正的。要清楚的是,我想做的就是基于一个字符串访问服务中的变量,该字符串等于variables name.Awesome。在Grails中也可以使用。@dmahapatro您在运行它时使用的是什么?这在很大程度上取决于上下文,因为对象是否会以OP询问的方式在中找到。这次我保存了脚本sayBarScript.groovy
@是的,因为这是一个脚本,所以必须从def foo=new foo()
中删除def
,才能使其在脚本中工作。很抱歉……没错,这很棘手,容易疏忽(至少对我来说)。但我仍然不理解使用“$foo”
而不是直接使用foo
背后的原理。询问OP关于它的情况。:)
// Cannot use `def` in a groovy-script when trying to do this
foo = new Foo()
def objectName = 'foo'
assert this."$objectName".someMethod() == "asdf"