MetaProgramming with Groovy II: ExpandoMetaClass
Join the DZone community and get the full member experience.
Join For FreeOn 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.
Opinions expressed by DZone contributors are their own.
Comments