GroovyInterceptable不适用于没有参数的方法

时间:2011-06-21 02:19:13

标签: groovy

一个简单的代码段,它将invokeMethod与GroovyInterceptable结合使用。如果嵌套的simpleMethod2有一个参数,它可以工作 - 否则不行。

我还没有找到解释,所以我认为它应该适用于没有参数的嵌套方法?

class SimpleFlow implements GroovyInterceptable {

    def invokeMethod(String name, args) {
        System.out.println("time before ${name} called: ${new Date()}")

        def calledMethod = SimpleFlow.metaClass.getMetaMethod(name, args)
        calledMethod?.invoke(this, args)

        System.out.println("time after ${name} called: ${new Date()}\n")
    }

    void simpleMethod1(){
        System.out.println("simpleMethod1() called")
        simpleMethod2Nested()
    }

    // works well when using an argument
    void simpleMethod2Nested(){
        System.out.println("simpleMethod2Nested")
    }

    public static void main(String[] args) {
        def flow = new SimpleFlow()
        flow.simpleMethod1()
    }
}

不带参数的输出:

time before simpleMethod1 called: Tue Jun 21 04:16:41 CEST 2011
simpleMethod1() called
simpleMethod2Nested
time after simpleMethod1 called: Tue Jun 21 04:16:41 CEST 2011`

1 个答案:

答案 0 :(得分:2)

还不确定它是否是一个错误或一个功能:)(最可能是一个错误,因为args的方法确实按预期工作 - 请在groovy jira中提出一个错误)。同时你可以通过添加引用self的变量this并使用它来调用嵌套方法来修复它:

class SimpleFlow implements GroovyInterceptable {

def self = this

def invokeMethod(String name, Object args) {
    // same as original
}

void simpleMethod1(){
    System.out.println("simpleMethod1() called")
    self.simpleMethod2Nested() // note the use of self
}

// works well when using an argument
void simpleMethod2Nested(){
    System.out.println("simpleMethod2Nested")
}

public static void main(String[] args) {
    def flow = new SimpleFlow()
    flow.simpleMethod1()
}

}

输出:

time before simpleMethod1 called: Tue Jun 21 13:32:44 GMT+08:00 2011
simpleMethod1() called
time before simpleMethod2Nested called: Tue Jun 21 13:32:44 GMT+08:00 2011
simpleMethod2Nested
time after simpleMethod2Nested called: Tue Jun 21 13:32:44 GMT+08:00 2011
time after simpleMethod1 called: Tue Jun 21 13:32:44 GMT+08:00 2011