6

私は以下を達成しようとしています:

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

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

A.mixin B
def a = new A()

a.foo() + a.bar()

1つの大きな違いがあります-インスタンスでミックスインを行いたいです:

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以降でこれを行うことができます

次のように、インスタンス metaClass で 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 に答える