【发布时间】:2013-09-08 09:39:56
【问题描述】:
我正在尝试使用元类访问实例的方法,但我收到属性不存在的错误。有没有办法访问在另一个类中声明的类的属性。
这是一个人为的例子:
class DogFood {
def ft = 'food!'
def foodType() { ft}
}
class Dog {
def bark() { println "woof!" }
DogFood df = new DogFood()
def ft() { println df.foodType()}
def getDf() {
df
}
}
def doAction( animal, action ) {
animal."$action"()
}
def rex = new Dog()
println rex.df.ft //works
def barkString = "bark"
doAction( rex, barkString ) //works
doAction( rex, "df.ft") //doesn't work
doAction( rex, "getDf().ft") //does not work
有没有办法使用 Groovy 的元类方法访问 df.ft 或 getDf().getFt()?
提前致谢
【问题讨论】:
-
但是你在哪里使用过元类?所看到的只是 GStrings 游戏。