本文介绍了实例上的Groovy Mixin(Dynamic Mixin)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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:没有方法的签名:A.mixin()适用于参数类型:(java.lang.Class)values:[class B] 

有没有办法让这个工作像在?

解决方案

您可以从Groovy 1.6



在实例metaClass上调用mixin如下:

  class A {
def foo() {foo}
}

class B {
def bar(){bar}
}

def a =新的A()
a.metaClass.mixin B

a.foo()+ a.bar()


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()

这篇关于实例上的Groovy Mixin(Dynamic Mixin)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 07:33