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:

  1.  
  2. import grails.converters.*
  3.  
  4. class TestController {
  5. def index = {
  6. [a:1, b:2, c:3] as JSON
  7. }
  8. }
  9.  
  10.  

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

  1.  
  2. class Foo {
  3. def name
  4.  
  5. String toString(){
  6. "Foo name is ${name}"
  7. }
  8. }
  9.  
  10. class Bar {
  11. def name
  12.  
  13. String toString(){
  14. "Bar name is ${name}"
  15. }
  16. }
  17.  
  18. class Bas {
  19.  
  20. def name
  21.  
  22. String toString(){
  23. "Bas name is ${name}"
  24. }
  25.  
  26. Object asType(Class type){
  27. typeWorker[type](this)
  28. }
  29.  
  30. @Lazy
  31. private def typeWorker = [(Foo):asFoo, (Bar):asBar]
  32.  
  33. private def asFoo = {it ->
  34. new Foo(name:it.name)
  35. }
  36.  
  37. private def asBar = {it ->
  38. new Bar(name:it.name)
  39. }
  40. }
  41.  
  42. def bas = new Bas(name:"Gringo")
  43.  
  44. println bas as Foo
  45. println bas as Bar
  46.  
  47.  

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 #

Sorry, the comment form is closed at this time.

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