在Groovy中向对象动态添加属性或方法 [英] Dynamically add a property or method to an object in groovy
问题描述
是否可以在Groovy中动态地向对象添加属性或方法?到目前为止,这是我尝试过的:
Is it possible to add a property or a method to an object dynamically in Groovy? This is what I have tried so far:
class Greet {
def name
Greet(who) { name = who[0].toUpperCase() + [1..-1] }
def salute() { println "Hello $name!" }
}
g = new Greet('world') // create object
g.salute() // Output "Hello World!"
g.bye = { println "Goodbye, $name" }
g.bye()
但是我得到以下异常:
Hello World!
Caught: groovy.lang.MissingPropertyException: No such property: bye for class: Greet
Possible solutions: name
at test.run(greet.groovy:11)
推荐答案
如果只想将bye()
方法添加到类Greet
的单个实例g
中,则需要执行以下操作:
If you just want to add the bye()
method to the single instance g
of the class Greet
, you need to do:
g.metaClass.bye = { println "Goodbye, $name" }
g.bye()
否则,要将bye()
添加到Greet
的所有实例(从现在开始),请调用
Otherwise, to add bye()
to all instance of Greet
(from now on), call
Greet.metaClass.bye = { println "Goodbye, $name" }
但是在创建Greet
类的实例
此外,您的构造函数中还有一个错误.您在[1..-1]
的前面缺少了who
,并且如果构造函数传递的长度小于2个字符的String
,则会抛出异常
Also, there's a bug in your constructor. You're missing who
from infront of your [1..-1]
and if the constructor is passed a String
of less than 2 characters in length, it will throw an exception
一个更好的版本可能是:
A better version might be:
Greet( String who ) {
name = who.inject( '' ) { String s, String c ->
s += s ? c.toLowerCase() : c.toUpperCase()
}
}
如评论所述,
As metioned in the comments,
Greet( String who ) {
name = who.capitalize()
}
是正确的方法
这篇关于在Groovy中向对象动态添加属性或方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!