开发者

Groovy Mixin on Instance (Dynamic Mixin)

开发者 https://www.devze.com 2022-12-24 16:47 出处:网络
I\'m trying to achieve following: class A { def foo() { \"foo\" } } class B { def bar() { \"bar\" } } A.开发者_运维问答mixin B

I'm trying to achieve following:

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

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

A.开发者_运维问答mixin B
def a = new A()

a.foo() + a.bar()

with one significant difference - I would like to do the mixin on the instance:

a.mixin B

but this results in

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

Is there a way to get this working like proposed in the Groovy Mixins JSR?


You can do this since Groovy 1.6

Call mixin on the instance metaClass like so:

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

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

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

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

精彩评论

暂无评论...
验证码 换一张
取 消