How to Use the Groovy Expando Class
The Expando
class in Groovy permits the developer to create an "expandable" class, i.e., a class to which fields and methods can be added as needed. This
technique is similar to how JavaScipt developers can create expandable objects by instantiating a variable of type Object
.
To learn how to use the Expando
class in Groovy, follow these 3 steps:
- Open your text editor and type in the following Groovy statements:
I've supplied comments to describe the use of the
// Define Expando class with two properties: def person = new Expando(firstName : "Stephen", lastName : "Withrow") // Add two more properties on the fly: person.email="sfw@webucator.com" // including a method property with a closure: person.toString={ return firstName + " " + lastName + " with email address " + email} println ("${person}")
Expando
object. The constructor uses a notation that is similar to defining maps in Groovy. Note that properties can be either fields or methods (implemented using closures). - Save your file as
UseGroovyExpandoClass.groovy
. - In the command prompt, type in the command to interpret and run your script:
The output displays the result of calling thetoString
method of the Expando object.