Creación Dinámica de Métodos

~/Lgroovy/objects$ cat -n dynamicmethodnamecreation.groovy 
     1  class Person {
     2     String name = "Fred"
     3  }
     4  
     5  def methodName = "to-Upper"
     6  
     7  Person.metaClass."${methodName}" = {-> 
     8     println "this = ${this.class.name}"
     9     println "owner = ${owner.class.name}"
    10     println "delegate = ${delegate.class.name}"
    11     delegate.name.toUpperCase() 
    12  }
    13  
    14  def p = new Person()
    15  
    16  println p.name
    17  
    18  println p.'to-Upper'()
    19  
    20  println p.name
~/Lgroovy/objects$ groovy dynamicmethodnamecreation.groovy 
Fred
this = dynamicmethodnamecreation
owner = dynamicmethodnamecreation
delegate = Person
FRED
Fred

Veamos otro ejemplo tomado de http://freeopenidea.blogspot.com/2009/02/dynamic-method-creation.html:

~/Lgroovy/objects$ cat -n DynamicMethodCreation.groovy 
     1  class CoolObject {
     2      public def invokeMethod(String name, def args) {
     3          if (name.startsWith("say")) {
     4              def words = []
     5              def currentWord = ""
     6  
     7              name.substring(3).each { letter ->
     8                  if (letter.equals(letter.toUpperCase())) {
     9                      words.add currentWord
    10                      currentWord = ""
    11                  }
    12                  currentWord += letter
    13              }
    14              words.add currentWord
    15  
    16              print "${args[0]} you are"
    17              words.collect {
    18                  it == "Dash" ? "-" : it
    19              }.each {
    20                  print "$it "
    21              }
    22              println ""
    23  
    24              return args[0]
    25          }
    26  
    27          super.invokeMethod(name, args)
    28      }
    29  }
    30  
    31  CoolObject coolObject = new CoolObject()
    32  
    33  println coolObject.saySomeoneCool("John")
    34  println coolObject.saySomeoneReallyDashReallyCool("Mary")
    35  println coolObject.toString()
~/Lgroovy/objects$ groovy DynamicMethodCreation.groovy 
John you are Someone Cool 
John
Mary you are Someone Really - Really Cool 
Mary
CoolObject@6c913dc1



Casiano Rodríguez León
2010-04-30