Groovy 动态添加带参数的方法

Groovy dynamically add method with argument

我想在现有的 class java.util.Date 中添加一个方法 "toFormatString(fmt)"。 我的代码如下:

Date.metaClass.toFormatString(String fmt) = {
  SimpleDateFormat sdf = new SimpleDateFormat(fmt)
  return sdf.format(delegate)
}

但是,Intellij 给我一个错误:分配给的值无效。

应该是:

import java.text.SimpleDateFormat

Date.metaClass.toFormatString = { String fmt ->
  SimpleDateFormat sdf = new SimpleDateFormat(fmt)
  return sdf.format(delegate)
}

assert new Date().toFormatString('yyyy') == '2015' //will work in 2015 only ;)