Here's a script from the Groovy book that explains expandos and makes some sense of why you might want to mess with spinning up methods at runtime. - http://groovy.codehaus.org/ExpandoMetaClass+-+Dynamic+Method+Names
The first example might help you pull off some interactive UI.
The second lends to a more fluid api.
Run that in your console and smoke it.
The first example might help you pull off some interactive UI.
The second lends to a more fluid api.
Run that in your console and smoke it.
import org.springframework.web.util.HtmlUtils
class HTMLCodec {
static encode = { theTarget ->
HtmlUtils.htmlEscape(theTarget.toString())
}
static decode = { theTarget ->
HtmlUtils.htmlUnescape(theTarget.toString())
}
}
//So what we do with these classes is to evaluate the convention and add
//"encodeAsXXX" methods to every object based on the first part of the
//name of the codec class such as "encodeAsHTML". The pseudo code to achieve this is below:
def classes = [HTMLCodec]
def codecs = classes.findAll { it.name.endsWith('Codec') }
codecs.each { codec ->
Object.metaClass."encodeAs${codec.name-'Codec'}" = { codec.newInstance().encode(delegate) }
Object.metaClass."decodeFrom${codec.name-'Codec'}" = { codec.newInstance().decode(delegate) }
}
def html = '<html><body>hello</body></html>'
println '<html><body>hello</body></html>' == HtmlUtils.htmlEscape(html)
//vs.
println '<html><body>hello</body></html>' == html.encodeAsHTML()
println html.encodeAsHTML()
Comments
Post a Comment