groovy - 如何将字符串转换为 Groovy 中的现有对象?
问题描述
如果我只知道现有对象的字面名称,如何调用它的方法?
例如:
class Cat {
def bark() {
println "I am a cat."
}
}
class Dog {
def bark() {
println "I am a dog."
}
}
def cat = new Cat()
def dog = new Dog()
def animal = 'cat'
"${animal}".bark() // Error
如下,我只知道动物的名字(可能是猫或狗)。我如何使用这个对象?
解决方案
如果cat
anddog
被定义为字段,您可以使用this
:
this."${animal}".bark()
或者
this[ animal ].bark()