Groovy 动态添加带参数的方法 [英] Groovy dynamically add method with argument
本文介绍了Groovy 动态添加带参数的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想向现有类 java.util.Date 添加一个方法toFormatString(fmt)".我的代码如下:
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)
}
但是,Intellij 给了我一个错误:要分配给的值无效.
However, Intellij gives me an error: Invalid value to assign to.
推荐答案
应该是:
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 ;)
这篇关于Groovy 动态添加带参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文