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:

  1. Open your text editor and type in the following Groovy statements:
    // Define Expando class with two properties:
    def person = new Expando(firstName : "Stephen", lastName : "Withrow")
    // Add two more properties on the fly:""
    // including a method property with a closure:
    person.toString={ return firstName + " " + lastName + " with email address " + email}
    println ("${person}")
    I've supplied comments to describe the use of the 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).
  2. Save your file as UseGroovyExpandoClass.groovy.
  3. In the command prompt, type in the command to interpret and run your script:
    Run Expando script
    The output displays the result of calling the toString method of the Expando object.
Author: Stephen Withrow

Stephen has over 30 years of experience in training, development, and consulting in a variety of technology areas including Python, Java, C, C++, XML, JavaScript, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen has a degree in Computer Science and Physics from Florida State University.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.