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屋!
查看全文