Groovy Meta programming

I have been playing around with Groovy for a while now. As a traditional Java developer, when I started playing with Groovy, I just fell in LOVE with it. Things just worked! It was really cool to see that there was a language that ran on JVM which was much more intuitive. (Groovy guys did an awesome job! Brought Coolness of other langs like Ruby, Python etc into a lang on JVM).

I am going to jump into a really cool feature of Groovy, ie. Meta programming. This concept was out of the ordinary for me but as I saw few use cases, I was really impressed.

Lets talk Expando! (Ref. Based on Webcast by Jeff Brown from springsource.)
Unlike Java, in groovy, lots of things happen at run time. One of them is to resolve proprety, method execution etc.
Here is an example.
Say, I create a groovy class:

Code 1.1

class ExpandoLite {


Say, I create an instance of the Class

Code 1.2

  def expandoLite = new ExpandoLite() = 'John'


// see no ; required... things are simple!

We will get an error

groovy.lang.MissingPropertyException: No such property: name for class: ExpandoLite

Groovy is dynamic, apparently Groovy calls a method called “setProperty” to set a property and getProperty to get the value off for it
So, we can do

class ExpandoLite {
	private dynamicProperties  = [:]

	void setProperty (String name, value){
		dynamicProperties[name] = value

        def getProperty (String name){

now if we run the code 1.2 again.
It will work

groovy> class ExpandoLite { 
groovy>     private dynamicProperties  = [:] 
groovy>     void setProperty (String name, value){ 
groovy>         dynamicProperties[name] = value 
groovy>     } 
groovy>     def getProperty (String name){ 
groovy>         dynamicProperties[name] 
groovy>     } 
groovy> } 
groovy> def expandoLite = new ExpandoLite() 
groovy> = 'John' 
groovy> println 

This feature allows us to dynamically create a field in the class. Behind the scene, we just have a map to store that stores value for a given attribute “Key”.