Groovy:运行期把方法mixin到对象实例

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: []')
}

 

你可能感兴趣的:(groovy)