How to Alter Behavior of Classes at Runtime with ExpandoMetaClass

  • google plus

In Brief...

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:

Instructions

  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: "sfw@webucator.com", 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);
    	sdf.format(person.birthDate)
    }
    // Display birth date first as day of the week and then as Month, day and 4-digit year	
    println("${person.displayBD("EEEE")}")
    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' 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