我想拦截一个类的所有方法(实例和静态),即使是缺少的类。
我们说:
class SomeClass {
def methodMissing(String name, args) {
if(name == "unknownMethod"){
return "result from unknownMethod"
}
else throw new MissingMethodException(name, delegate, args)
}
}
SomeClass.metaClass.static.invokeMethod = { methodName, args ->
println "Before"
def result = delegate.metaClass.invokeMethod(delegate, methodName, *args)
println "After"
return result
}
new SomeClass().with{ sc ->
sc.unknownMethod() //throw the MissingMethodExcept
}
这适用于由类实现的方法,但是当它是methodMissing处理的方法时,我得到一个MissingMethodException ......
你会怎么做?
提前致谢
答案 0 :(得分:2)
我认为你需要捕捉非静态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]