I wanted to add the methodMissing()
to a class which I don't have source code control over. I've tried:
我想将methodMissing()添加到一个我没有源代码控制的类中。我试过了:
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: []
但我仍然得到一个groovy.lang.MissingMethodException:没有方法签名:MyClass.nonexisting()适用于参数类型:()值:[]
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.
我试图避免混淆元类,因为这种变化将是全局的,不可逆的。
1 个解决方案
#1
2
According to Groovy in Action, 2nd Edition published in 2015:
根据Groovy in Action,2015年第2版发布:
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.
类别方法名称可以采用属性访问器(假装属性访问),运算符方法和GroovyObject方法的形式。 MOP钩子方法(propertyMissing,methodMissing)不能通过类别类添加。这是Groovy 2.4的限制。该功能可能会在以后的版本中提供。
So it's not possible to do it in 2.4.12,
所以在2.4.12中不可能这样做,
The release notes for Groovy 2.5 (still in development as 2017-11) don't mention any changes regarding this.
Groovy 2.5的发行说明(仍在开发中,作为2017-11)没有提及任何相关的变化。
The release notes for Groovy 2.6 don't mention it either.
Groovy 2.6的发行说明也没有提到它。
And finally unfortunately the release notes for Groovy 3.0 say nothing about methodMissing
最后不幸的是,Groovy 3.0的发行说明没有提及methodMissing
#1
2
According to Groovy in Action, 2nd Edition published in 2015:
根据Groovy in Action,2015年第2版发布:
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.
类别方法名称可以采用属性访问器(假装属性访问),运算符方法和GroovyObject方法的形式。 MOP钩子方法(propertyMissing,methodMissing)不能通过类别类添加。这是Groovy 2.4的限制。该功能可能会在以后的版本中提供。
So it's not possible to do it in 2.4.12,
所以在2.4.12中不可能这样做,
The release notes for Groovy 2.5 (still in development as 2017-11) don't mention any changes regarding this.
Groovy 2.5的发行说明(仍在开发中,作为2017-11)没有提及任何相关的变化。
The release notes for Groovy 2.6 don't mention it either.
Groovy 2.6的发行说明也没有提到它。
And finally unfortunately the release notes for Groovy 3.0 say nothing about methodMissing
最后不幸的是,Groovy 3.0的发行说明没有提及methodMissing