methodMissing and propertyMissing
When a Groovy object receives a call it does not declare, the runtime looks for methodMissing before it gives up. A class that defines it can answer a family of names, which is how a builder knows a method that was never written.
A method that is not there
method.groovy
class Recorder {
def methodMissing(String name, args) {
"called ${name} with ${args.join(', ')}"
}
}
def recorder = new Recorder()
println recorder.publish('pdf')
println recorder.archive('2026', 'groovy')
groovy method.groovy
called publish with pdf
called archive with 2026, groovy
The first argument is the name that was called and the second is the argument list. The return value is the value of the call, so a missing method is indistinguishable from a real one to the caller.
A property that is not there
property.groovy
class Settings {
private Map<String, Object> values = [:]
def propertyMissing(String name) {
values[name]
}
void propertyMissing(String name, value) {
values[name] = value
}
Map<String, Object> asMap() {
values
}
}
def settings = new Settings()
settings.theme = 'dark'
settings.fontSize = 14
println settings.theme
println settings.fontSize
println settings.missing
println settings.asMap().sort()
groovy property.groovy
dark
14
null
[fontSize:14, theme:dark]
Two overloads cover the two directions: a read calls the one-argument form and a write the two-argument form. The class keeps its values in a map, so a typo in a name adds an entry instead of failing, which is the risk of the pattern as much as its use.
The error without them
A class with neither hook throws MissingMethodException. The message names the method, the class and the argument types, which is everything a debugger needs:
typo.groovy
class Plain {
String title = 'x'
}
println new Plain().publish()
groovy typo.groovy
Caught: groovy.lang.MissingMethodException: No signature of method: publish for class: Plain is applicable for argument types: () values: []
groovy.lang.MissingMethodException: No signature of method: publish for class: Plain is applicable for argument types: () values: []
at typo.run(typo.groovy:5)
exit status: 1
The first line of the trace is the message, and the frame below names the line of the call. A class that defines methodMissing never reaches this error, so a typo becomes a new "method" that answers with a string, and a page that uses the trick needs a test for the names it expects.
Related
- ExpandoMetaClass and categories: a method added to a class you do not own.
- A small DSL: the hook that makes a builder read like a language.
Автор статьи: Arthur Isaev