Groovy 动态添加带参数的方法

wur*_*eka 3 methods groovy arguments dynamic

我想向现有的类 java.util.Date 添加一个方法“toFormatString(fmt)”。我的代码如下:

Date.metaClass.toFormatString(String fmt) = {
  SimpleDateFormat sdf = new SimpleDateFormat(fmt)
  return sdf.format(delegate)
}
Run Code Online (Sandbox Code Playgroud)

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

Opa*_*pal 5

它应该是:

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 ;)
Run Code Online (Sandbox Code Playgroud)