Reputation: 24806
I wanted to add the methodMissing()
to a class which I don't have source code control over. I've tried:
class MyClass {} // class I'm not allowed to edit
class MyCategory {
static def methodMissing(MyClass self, String name, Object args) {
"I was hoping this was called on a.nonexisting()"
}
static def test(MyClass self) {
"test works"
}
}
def a = new MyClass()
use(MyCategory) {
println a.test()
println a.nonexisting()
}
But I still get a groovy.lang.MissingMethodException: No signature of method: MyClass.nonexisting() is applicable for argument types: () values: []
Is it possible to add a temporary methodMissing
to a class?
I was trying to avoid to mess with the meta class since that change will be global and non-reversible.
Upvotes: 1
Views: 91
Reputation: 24806
According to Groovy in Action, 2nd Edition published in 2015:
Category method names can well take the form of property accessors (pretending property access), operator methods, and GroovyObject methods. MOP hook methods (propertyMissing, methodMissing) cannot be added through a category class. This is a restriction as of Groovy 2.4. The feature may become available in later versions.
So it's not possible to do it in 2.4.12,
The release notes for Groovy 2.5 (still in development as 2017-11) don't mention any changes regarding this.
The release notes for Groovy 2.6 don't mention it either.
And finally unfortunately the release notes for Groovy 3.0 say nothing about methodMissing
Upvotes: 2