Groovy Mixin on Instance(Dynamic Mixin)

dav*_*vid 6 groovy dynamic instance mixins

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

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

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

A.mixin B
def a = new A()

a.foo() + a.bar()
Run Code Online (Sandbox Code Playgroud)

有一个显着的区别 - 我想在实例上做mixin:

a.mixin B
Run Code Online (Sandbox Code Playgroud)

但这会导致

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

有没有办法像Groovy Mixins JSR中提出的那样工作?

tim*_*tes 8

你可以从Groovy 1.6开始这样做

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

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

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

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

a.foo() + a.bar()
Run Code Online (Sandbox Code Playgroud)