Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.


Since Groovy allows you to use Strings as property names this in turns allows you to dynamically create method and property names at runtime. For example in

The Basics

To create a method with a dynamic name simply use Groovy's feature of reference property names as strings. You can combine this with Groovy's string interpolation (Gstrings) to create method and property names on the fly:

Code Block

class Person {
   String name = "Fred"

def methodName = "Bob"

Person.metaClass."changeNameTo${methodName}" = {-> = "Bob" } 

def p = new Person()

assert "Fred" ==


assert "Bob" ==

The same concept can be applied to static methods and properties.

A more elaborate example

In Grails we have a concept of dynamic codecs, classes that can encode and decode data.