Groovy Grails - Dynamic Method n Variable name and invoking them

Groovy allows to use dynamic method name and variable name and invoke/use them.

Dynamic Variable Names

Groovy allows to use variable name dynamically. To test this lets introduce a variable  "dogname" to Dog class

class Dog {
def dogname
...
}

//Testing dynamic variable name
        def aDog= new Dog()
aDog.name="Hachi"
def prop="dogname"

println aDog."$prop" // prints Hachi



Dynamic Method Invocation :

You can invoke a method even if you don't know the method name until it is invoked: In the example below, we are executing the method in the Dog class without knowing the method name in advance. We are simply passing a String to the method doAction as doAction( rex, "bark" ) and inside doAction method, we are calling the actual function whose name is fromed based on the second parameter to the doAction method - action. -> animal."$action"()

//dog class

class Dog {
  def bark() { println "woof!" }
  def sit() { println "(sitting)" }
  def jump() { println "boing!" }
}

def doAction( animal, action ) {
    //creating the method name out of the action parameter 
  animal."$action"()                  //action name is passed at invocation
}

def rex = new Dog()

doAction( rex, "bark" )               //prints 'woof!'
doAction( rex, "jump" )               //prints 'boing!'


Reference: http://groovy.codehaus.org/Dynamic+Groovy

No comments :

Post a Comment

Your Comment and Question will help to make this blog better...