Posted By

hansamann on 06/20/07


Tagged

groovy beans groovybeans expando javabeans


Versions (?)

Who likes this?

8 people have marked this snippet as a favorite

tch
jsbournival
bootz15
hendersk
mbanfi
doctorillo
adaptives
laurenceosx


Groovy Series: GroovyBeans & Expando


 / Published in: Groovy
 

URL: http://hansamann.podspot.de/files/grails_podcast_episode_42.mp3

This snippet gives you some interesting examples about GroovyBeans and Expando. Listen to the audio to get the best learning experience. Simply right-click on the title above to download the mp3 file of this part of the series.

The Groovy Series is part of the Grails Podcast and can be subscribed to via: http://hansamann.podspot.de/rss. The series is produced by Dierk K├Ânig and Sven Haiges, further information about the topic of this episode can be found in the book

Groovy in Action - http://groovy.canoo.com/gina

  1. //GroovyBeans are JavaBeans, just made easier. What exactly is the advantage?
  2.  
  3. //simple groovybean -> note Serializable!
  4. class SimpleBean implements java.io.Serializable
  5. {
  6. String myProperty
  7. }
  8. def bean1 = new SimpleBean()
  9. bean1.myProperty = "groovy"
  10. assert bean1.myProperty == "groovy"
  11.  
  12. bean1.setMyProperty("grails")
  13. assert bean1.getMyProperty() == "grails"
  14.  
  15. //another bean, just no "javabean"
  16. class AnotherBean
  17. {
  18. def prop1, prop2, prop3
  19. }
  20.  
  21. new AnotherBean(prop1:"one")
  22.  
  23. def bean2 = new AnotherBean()
  24. assert bean2.prop1 == null
  25. bean2.prop1 = "one"
  26. assert bean2.prop1 == "one"
  27.  
  28. //access to all properties... interestingly "properties" is not a property
  29. bean2.properties.each { name, value -> println "Property: $name -> $value" }
  30.  
  31. //direct field access with .@ operator - dot at
  32. //plus example of using map constructor
  33. class HackedBean
  34. {
  35. String someValue
  36.  
  37. def getSomeValue()
  38. {
  39. return "always the same"
  40. }
  41.  
  42. def internalSomeValue()
  43. {
  44. return this.@someValue
  45. }
  46. }
  47. def bean3 = new HackedBean(someValue:'blubb')
  48. assert bean3.internalSomeValue() == 'blubb'
  49. assert bean3.someValue == 'always the same'
  50.  
  51. // Expando magic.
  52. def dyn = new Expando()
  53. assert dyn.prop1 == null
  54. ['one','two','three'].each {
  55. dyn."$it" = it //dyn[it] = it
  56. }
  57. assert dyn.one == "one"
  58. assert dyn.two == "two"
  59. assert dyn.three == "three"
  60.  
  61. //it even gets better: you can assign "methods" by setting closures
  62. dyn.sayHello = { name -> return "Hello $name" }
  63. assert dyn.sayHello('Martin') == "Hello Martin"

Report this snippet  

You need to login to post a comment.