DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more
  1. DZone
  2. Coding
  3. Languages
  4. MetaProgramming with Groovy II: ExpandoMetaClass

MetaProgramming with Groovy II: ExpandoMetaClass

Andres Almiray user avatar by
Andres Almiray
·
Feb. 10, 08 · Interview
Like (1)
Save
Tweet
Share
29.86K Views

Join the DZone community and get the full member experience.

Join For Free

On the second part of this series learn about ExpandoMetaClass, a special MetaClass that will let you update and tweak the behavior of classes in runtime.

Introduction

We saw on the first part that Groovy provides a MetaClass for each class, and that you may modify the behavior of classes with Categories, which as easy to use as they look are usually associated with a temporal scope. ExpandoMetaClass on the other hand may provide a more permanent updated behavior (as long as your application/script is still running).

Skimming the Surface 

Let's revisit the commons-lang example, adding a capitalize() and normalize() methods to String using a Category, this time we will not use StringUtils as category by itself but create our own StringCategory.

import org.apache.commons.lang.StringUtils  

class StringCategory {
static capitalize( String self ){
StringUtils.capitalize(self)
}

static normalize( String self ){
self.split("_").collect { word ->
word.toLowerCase().capitalize()
}.join("")
}
}

use( StringCategory ){
assert "Groovy" == "groovy".capitalize()
assert "CamelCase" == "CAMEL_CASE".normalize()
} 

Remember that if you try to call any of those methods outside use() an exception will be thrown. Now for the ExpandoMetaClass version

import org.apache.commons.lang.StringUtils  

String.metaClass.capitalize = {
StringUtils.capitalize(delegate)
}

String.metaClass.normalize = {
delegate.split("_").collect { word ->
word.toLowerCase().capitalize()
}.join("")
}

assert "Groovy" == "groovy".capitalize()
assert "CamelCase" == "CAMEL_CASE".normalize()

Notice the subtle changes, no parameter is required for the capitalize and normalize methods because instead of self we are using the closure's delegate as the target object the method will act upon, aside from that the behavior code is identical. The main difference is how these methods are registered with the MOP system. In the case of ExpandoMetaClass you may add a new method, or update/overload an existing one by assigning a closure as a property of the MetaClass. Let's see another example, starting with a simple (very simple) POGO that has only one property.

class Person {
String name
}

Person.metaClass.greet = {
"Hello, I'm $name"
}
def duke = new Person(name:'Duke')
assert duke.greet() == "Hello, I'm Duke"

Nothing fancy but helpful, now let's try adding a new method and overload it at the same time

Person.metaClass.whatIsThis = { String arg ->
"it is a String with value '$arg'"
}
Person.metaClass.whatIsThis << { int arg ->
"it is an int with value $arg"
}

assert duke.whatIsThis( 'Groovy' ) == "it is a String with value 'Groovy'"
assert duke.whatIsThis( 12345 ) == "it is an int with value 12345"

First we define a whatIsThis() method that takes a String as parameter (notice that we use = to assign the closure to the metaclass property), then we add an overloaded version that takes an int as parameter, note that we use the leftShit operator to add the new method, if we had used the assign operator we would have overwritten and not overloaded whatIsThis(). What if we decided to overload the method a second time but do not specify a type? what would happen?

Person.metaClass.whatIsThis << { arg ->
"I don't know what $arg is"
}

assert duke.whatIsThis( 1.0 ) == "I don't know what 1.0 is"
assert duke.whatIsThis( 'Groovy' ) == "it is a String with value 'Groovy'"
assert duke.whatIsThis( 12345 ) == "it is an int with value 12345"

Thanks to Groovy's dynamic dispatch the correct overloaded method is found and called. 

Diving deeper

Groovy's MOP system includes some extension/hooks points that you can use to change how a class or an object behaves, mainly being

  • getProperty/setProperty: control property access
  • invokeMethod: controls method invocation, you can use it to tweak parameters of existing methods or intercept not-yet existing ones
  • methodMissing: the preferred way to intercept non-existing methods
  • propertyMissing: also the preferred way to intercept non-existing properties

Let's intercept all method calls using invokeMethod, even for those methods that were not really defined in our test class

class Person {
String name
String sayHello( toWhom ){ "Hello $toWhom" }
}

Person.metaClass.invokeMethod = { String name, args ->
"$name() called with $args"
}

def duke = new Person(name:'Duke')
assert duke.sayHello('world') == 'sayHello() called with {"world"}'
assert duke.greet() == 'greet() called with {}'
assert duke.greet('world') == 'greet() called with {"world"}'

Now let's try the same but this time using methodMissing

class Person {
String name
String sayHello( toWhom ){ "Hello $toWhom" }
}

Person.metaClass.methodMissing = { String name, args ->
"$name() called with $args"
}

def duke = new Person(name:'Duke')
assert duke.sayHello('world') == 'Hello world'
assert duke.greet() == 'greet() called with {}'
assert duke.greet('world') == 'greet() called with {"world"}'

This time the previously existing sayHello() method was not intercepted, because it really was defined in the test class, but the greet() methods weren't so they get intercepted. Adding new properties may be trickier than you think, specially when it comes to storing the value you set for these new properties. Due to implementation details you may need to use more permanent storage like a synchronized Map, as properties may be added to the MetaClass but may be garbage collected without you knowing about it (see here for an explanation). There are other things ExpandoMetaClass will let you do, like overloading static methods, please look into ExpandoMetaClass's documentation to know more about these features.

The Catch

ExpandoMetaClass is a great improvement over what Groovy previously provided in the custom metaclass department, but it also comes with its quirks, for example inheritance is not enabled by default (because it will cause a performance hit), the following code will fail despite its simplicity

class Person {
String name
}
class Employee extends Person {
int employeeId
}

Person.metaClass.greet = { -> "Hello!" }

def duke = new Person(name:'Duke')
assert duke.greet() == "Hello!"
def worker = new Employee(name:'Drone1')
// the following line causes an exception!!
assert worker.greet() == "Hello!"

The workaround is enabled by calling ExpandoMetaClass.enableGlobally(), but use it judiciously.

Conclusion

ExpandoMetaClass has a longer lifespan than a category, it can also affect subclasses as categories do albeit with a penalty. Nevertheless it is a great addition to the language, originally forged on the Grails project.

Groovy (programming language) Metaprogramming

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • GitLab vs Jenkins: Which Is the Best CI/CD Tool?
  • Cucumber.js Tutorial With Examples For Selenium JavaScript
  • Using GPT-3 in Our Applications
  • 3 Main Pillars in ReactJS

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: