在Ruby中,我可以通过打开它来为类添加实例变量,并执行以下操作:
class Whatever
def add_x
@x = 20
end
end
这将为我添加一个名为x的实例变量。我怎么能在Groovy中做同样的事情呢?
答案 0 :(得分:3)
您可以使用Groovy的元类:
class Foo { String bar }
f = new Foo(bar:"one")
f.metaClass.spam = "two"
f.spam == "two" // returns true
f.spam = "eggs" // Change property value
f.spam == "eggs" //returns true