ExpandoMetaClass - Dynamic Method Names Add comment to Wiki View in Wiki Edit Wiki page Printable Version

ExpandoMetaClass - Dynamic method/property name creation

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

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:

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.

These classes are called HTMLCodec, JavaScriptCodec etc. an example of which can be seen below:

So what we do with these classes is to evaluate the convention and add "encodeAsXXX" methods to every object based on the first part of the name of the codec class such as "encodeAsHTML". The pseudo code to achieve this is below:

As you can see from the above we dynamically construct the names of the methods using GString expressions!



Results of your search request can come from various sources: the Groovy website itself, the JIRA issues, the API documentation, as well as a few other interesting Groovy-related blogs.

  By  -  pages  -  views  - last modified