Groovy:运行期把方法mixin到对象实例
从Groovy 2.1 开始我们可以在运行期把方法mixin到对象实例。这个mixin和class的mixing用法很不一样,他需要调用对象实例的metaClass属性的mixin方法。
class Parrot {
static String speak(String text) {
/"$text" Polly wants a cracker!/
}
}
// Runtime mixin on String object instead of class.
String s = 'Groovy is Gr8'
s.metaClass.mixin Parrot
assert s.speak() == '"Groovy is Gr8" Polly wants a cracker!'
String other = 'Groovy and Grails'
try {
other.speak()
} catch (MissingMethodException e) {
assert e.message.startsWith('No signature of method: java.lang.String.speak() is applicable for argument types: () values: []')
}
本文介绍如何在Groovy2.1中实现在运行时将方法动态地混入到对象实例的过程。通过使用对象实例的metaClass属性的mixin方法,可以为特定实例增加新的行为而不影响其他实例。
1020

被折叠的 条评论
为什么被折叠?



