我认为你需要赶上非静态invokeMethod
以及
此外,您还需要经过getMetaMethod
调用原始方法,否则你运行stackoverflows的风险。
考虑以下几点:
class SomeClass {
String name
static String joinWithCommas(a, b, c) {
[ a, b, c ].join(',')
}
String joinAfterName(a, b, c) {
"$name : ${SomeClass.joinWithCommas(a, b, c)}"
}
def methodMissing(String name, args) {
if(name == "unknownMethod"){
return "result from unknownMethod"
}
else {
throw new MissingMethodException(name, SomeClass, args)
}
}
}
// Return a closure for invoke handler for a class
// with a given title (for the logging)
def invokeHandler = { clazz, title ->
{ String methodName, args ->
println "Before $methodName ($title)"
def method = clazz.metaClass.getMetaMethod(methodName, args)
def result = method == null ?
clazz.metaClass.invokeMissingMethod(delegate, methodName, args) :
method.invoke(delegate, args)
println "After $methodName result = $result"
result
}
}
SomeClass.metaClass.invokeMethod = invokeHandler(SomeClass, 'instance')
SomeClass.metaClass.static.invokeMethod = invokeHandler(SomeClass, 'static')
new SomeClass(name:'tim').with { sc ->
sc.joinAfterName('a', 'b', 'c')
sc.unknownMethod('woo', 'yay')
sc.cheese('balls')
}
我得到的输出:
Before with (instance)
Before joinAfterName (instance)
Before joinWithCommas (static)
After joinWithCommas result = a,b,c
After joinAfterName result = tim : a,b,c
Before unknownMethod (instance)
After unknownMethod result = result from unknownMethod
Before cheese (instance)
Exception thrown
groovy.lang.MissingMethodException: No signature of method: SomeClass.cheese() is applicable for argument types: (java.lang.String) values: [balls]
我尝试,并让你知道 – Fiftoine 2013-04-09 10:41:06
的问题保持不变,当方法未实现,但被处理通过methodMissing,getMetaMethod返回null,但调用它没有拦截返回的东西... – Fiftoine 2013-04-09 10:49:36
@Fiftoine哦...你*想*一个'MissingMethodException抛出? – 2013-04-09 10:50:42