2010-03-21 10 views
6

我试图做到以下几点:Groovy的密新的实例(动态密新)

class A { 
    def foo() { "foo" } 
} 

class B { 
    def bar() { "bar" } 
} 

A.mixin B 
def a = new A() 

a.foo() + a.bar() 

一个显著差异 - 我想这样做实例上的mixin:

a.mixin B 

但这导致

groovy.lang.MissingMethodException: No signature of method: A.mixin() is applicable for argument types: (java.lang.Class) values: [class B] 

有没有办法让这个喜欢在Groovy Mixins JSR建议的工作?

回答

8

您可以在实例的metaClass做到这一点,因为Groovy 1.6中

呼叫混入像这样:

class A { 
    def foo() { "foo" } 
} 

class B { 
    def bar() { "bar" } 
} 

def a = new A() 
a.metaClass.mixin B 

a.foo() + a.bar() 
+0

非常感谢添!所以我不得不等待一下,直到Groovy 1.7.1是Grails的一部分(我们希望在1.3中)... – david 2010-03-21 20:17:34

+1

刚刚尝试过,它也适用于1.6.3(我相信它是groovy的版本grails 1.2使用):-) – 2010-03-21 22:17:09

+1

是的,这个特性在Groovy 1.6中加入了 http://www.infoq.com/articles/groovy-1-6 – 2010-03-22 14:36:58