Groovy dynamically add method with argument

独自空忆成欢 提交于 2019-12-11 02:48:50

问题


I want add a method "toFormatString(fmt)" to the existed class java.util.Date. My code is below:

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

However, Intellij gives me an error: Invalid value to assign to.


回答1:


It should be:

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


来源:https://stackoverflow.com/questions/29270027/groovy-dynamically-add-method-with-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!