How to Use the Groovy Expando Class

  • google plus

In Brief...

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:

Instructions

  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:
    person.email="sfw@webucator.com"
    // 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' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss