Groovy Mixin使用混合类的方法

时间:2013-05-22 20:15:50

标签: groovy mixins

考虑一个mixin类

class StringPlusMixin {
  String plus(String other) {
    return toString() + other
  }
}

他的用例

@Mixin(StringPlusMixin)
class POGO {
  String descr
  String toString(){
    return descr
  }
}

有没有办法让SringPlusMixin使用POGO#toString()代替SringPlusMixin#toString()

实际输出是:

POGO pogo = new POGO(descr: "POGO description");
System.out.println(pogo + "Some message."); //StringPlusMixin@f410f8 Some message.

我正在考虑使用此mixin,因为Groovy默认的instance + String是尝试调用plus()方法。我在几个Java类中使用我的POGO并尝试不需要更改所有消息以使用toString()

2 个答案:

答案 0 :(得分:2)

反射?此外,我将您的类转换为类别,方法是将方法设为静态并将子对象作为第一个参数传递。

更新:根据评论,从mixin方法中删除了类型

import org.codehaus.groovy.runtime.InvokerHelper as Invoker

class StringPlusMixin {
  static String plus(pogo, String other) {
    def toString = pogo.class.declaredMethods.find { it.name == "toString" }
    return toString.invoke(pogo) + other
  }
}


@Mixin(StringPlusMixin)
class POGO {
  String descr
  String toString(){
    return descr
  }
}


pogo = new POGO(descr: "POGO description")
assert pogo + " Some message." == "POGO description Some message."

答案 1 :(得分:2)

在POGO中使用@Delegate转换。

@Mixin(StringPlusMixin)
class POGO {
  @Delegate String descr
  String toString(){
    return descr
  }
}

由于descr归POGO所有,因此在运行时使用descr会将所有权分配给POGO。

相关问题