Groovy元编程-截取所有方法,甚至截取丢失的方法

Groovy元编程-截取所有方法,甚至截取丢失的方法,groovy,metaprogramming,Groovy,Metaprogramming,我想截取一个类的所有方法(实例和静态),甚至是缺少的方法 可以这样说: class SomeClass { def methodMissing(String name, args) { if(name == "unknownMethod"){ return "result from unknownMethod" } else throw new MissingMethodException(name, delegat

我想截取一个类的所有方法(实例和静态),甚至是缺少的方法

可以这样说:

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

你会怎么做


提前感谢

我认为您还需要捕获非静态的
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]

我试着这么做,让你知道问题是一样的,当这个方法没有实现,但是被methodMissing处理时,getMetaMethod返回null,但是在没有拦截的情况下调用它会返回一些东西…@Fiftoine哦…你想抛出一个
MissingMethodException
吗?@Fiftoine好的,我改变了我的答案。。。这就是你的意思吗?@Fiftoine它能做什么?