How to Alter Behavior of Classes at Runtime with ExpandoMetaClass

What if you wanted to add functionality to a Groovy class? How would you accomplish this task? The answer: use the ExpandoMetaClass! With this class you can add one or more methods to an existing class definition. For example, a common challenge in human resources data processing is formatting a hire date or birth date in different ways. Of course, the developer could instantiate different date formats manually but there is no need to do that if you correctly leverage the ExpandoMetaClass. In this topic, I'll show you how to pull off this neat trick.

To learn how to alter the behavior of classes at runtime using the ExpandoMetaClass in Groovy, follow these three steps:

  1. Open your text editor and type in the following Groovy statements:
    import java.text.*
    // Define Person class 
    class Person {
    	String lastName
    	String firstName
    	String emailAddress
    	Date birthDate
    	public String toString() {
    		"Name: $lastName, $firstName Email: $emailAddress Birth date: $birthDate"
    // Create a person object
    def person = new Person(firstName : "Stephen", lastName : "Withrow", emailAddress: "", birthDate: new Date().parse("yyyy/MM/dd", "1955/03/16"))
    // Add a method at runtime to display birthdate in a given format
    person.metaClass.displayBD { formt -> def sdf = new SimpleDateFormat(formt);
    // Display birth date first as day of the week and then as Month, day and 4-digit year	
    println("${person.displayBD("MMM dd, yyyy")}")
    // Finally, display the person
    println ("${person}")
    I've supplied comments to describe the use of the ExpandoMetaClass class. Note that the class is exposed through the metaClass property that is available for every class. The method logic is implemented using a closure and accepts as input a string that specifies the date format to use with SimpleDateFormat. Two date formats are tested: EEEE to request day of the week (e.g., Friday) and MMM dd, yyyy to request a familiar way of displaying date (e.g., Sep 29, 2017).
  2. Save your file as UseGroovyExpandoMetaClass.groovy.
  3. In the command prompt, type in the command to interpret and run your script:
    Run ExpandoMetaClass script
    The output displays the birth date as day of week and then as the common presentation of month. day and year. The next part of the output is the result of calling the toString method of the Person 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.