Metaprogramming and methodMissing
Site Admin
· 11 Sep 2026
· 8 views
What is Metaprogramming?
Metaprogramming is writing code that modifies or extends the behavior of other code at runtime. Groovy provides powerful metaprogramming capabilities that let you intercept method calls, add methods to existing classes, and create dynamic behaviors.
methodMissing
The methodMissing hook is called when you invoke a method that does not exist on an object:
class DynamicUser {
def properties = [:]
def methodMissing(String name, args) {
if (name.startsWith("get")) {
def prop = name.substring(3).toLowerCase()
return properties[prop]
}
throw new MissingMethodException(name, this.class, args)
}
}
def user = new DynamicUser()
user.properties["name"] = "Alice"
println user.getName() // Alice
ExpandoMetaClass
You can add methods to existing classes at runtime using ExpandoMetaClass:
String.metaClass.shout = { ->
delegate.toUpperCase() + "!"
}
println "hello".shout() // HELLO!
// Add to existing classes
Integer.metaClass.isEven = { ->
delegate % 2 == 0
}
println 4.isEven() // true
propertyMissing
Similar to methodMissing, propertyMissing handles undefined property access:
class Flexible {
def data = [:]
def propertyMissing(String name) {
return data[name]
}
def propertyMissing(String name, value) {
data[name] = value
}
}
def obj = new Flexible()
obj.customField = "test"
println obj.customField // test
Key Points
methodMissingintercepts calls to non-existent methods.ExpandoMetaClasslets you add methods to existing classes.propertyMissinghandles undefined property access.- Metaprogramming enables dynamic DSL creation.
- Use these features carefully - they can make code harder to debug.