Googling around for Groovy ways to "cast" a String
to a Date
, I came across this article:
http://www.goodercode.com/wp/intercept-method-calls-groovy-type-conversion/
The author uses Groovy metaMethods to allow dynamically extending the behavior of any class' asType
method. Here is the code from the website.
class Convert {
private from
private to
private Convert(clazz) { from = clazz }
static def from(clazz) {
new Convert(clazz)
}
def to(clazz) {
to = clazz
return this
}
def using(closure) {
def originalAsType = from.metaClass.getMetaMethod('asType', [] as Class[])
from.metaClass.asType = { Class clazz ->
if( clazz == to ) {
closure.setProperty('value', delegate)
closure(delegate)
} else {
originalAsType.doMethodInvoke(delegate, clazz)
}
}
}
}
They provide a Convert
class that wraps the Groovy complexity, making it trivial to add custom as
-based type conversion from any type to any other:
Convert.from( String ).to( Date ).using { new java.text.SimpleDateFormat('MM-dd-yyyy').parse(value) }
def christmas = '12-25-2010' as Date
It's a convenient and powerful solution, but I wouldn't recommend it to someone who isn't familiar with the tradeoffs and pitfalls of tinkering with metaClasses.