invokeMethod
非静的もキャッチする必要があると思います
また、元のメソッドを呼び出すために通過する必要がありますgetMetaMethod
。そうしないと、スタックオーバーフローのリスクが発生します。
以下を考えると:
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]