6

我正在努力实现以下目标:

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中提议的那样工作?

4

1 回答 1

8

从 Groovy 1.6 开始你就可以这样做了

在实例元类上调用 mixin,如下所示:

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

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

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

a.foo() + a.bar()
于 2010-03-21T18:39:33.973 回答