2

我想拦截一个类的所有方法(实例和静态),甚至是丢失的方法。

让我们说:

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 ...

你会怎么做?

提前致谢

4

1 回答 1

2

我认为你也需要捕捉非静态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]
于 2013-04-09T09:45:47.587 回答