Groovy magic: asType

Every one who used Grails had to deal (or will have) with XML/JSON converters. They allow to transform object by using syntax like:

 
import grails.converters.*
 
class TestController {
    def index = {
         [a:1, b:2, c:3] as JSON
    }
}
 

I like this "as" syntax, is very verbose and clear. How we can implement in our code? Simple, just use asType method:

 
class Foo {
    def name
 
    String toString(){
        "Foo name is ${name}"
    }
}
 
class Bar {
    def name
 
    String toString(){
        "Bar name is ${name}"
    }
}
 
class Bas {
 
    def name
 
    String toString(){
        "Bas name is ${name}"
    }
 
    Object asType(Class type){
        typeWorker[type](this)
    }
 
    @Lazy
    private def typeWorker = [(Foo):asFoo, (Bar):asBar]
 
    private def asFoo = {it ->
        new Foo(name:it.name)
    }
 
    private def asBar = {it ->
        new Bar(name:it.name)
    }
}
 
def bas = new Bas(name:"Gringo")
 
println bas
println bas as Foo
println bas as Bar
 

and output will be :

Bas name is Gringo
Foo name is Gringo
Bar name is Gringo

1 Comment »

RSS feed for comments on this post.

  1. Nice tip. Thanks for sharing!

    Comment by Joshua Moore — August 17, 2010 #

Leave a comment

XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*

Powered by WordPress with GimpStyle Theme design by Horacio Bella.
Entries and comments feeds. Valid XHTML and CSS.