Groovy:使用GroovyInterceptable的println与System.out.println

Cel*_*elt 5 groovy

为什么需要使用System.out.println而不是println何时使用GroovyInterceptable

例如,如果我在Groovy文件中编码,则可以通过键入以下内容打印到控制台:

println "Printing to Console"
Run Code Online (Sandbox Code Playgroud)

但是,如果我想在这里打印:

class Test implements GroovyInterceptable {
    def sum(Integer x, Integer y) { x + y }

    def invokeMethod(String name, args) {
        System.out.println "Invoke method $name with args: $args"
    }
}

def test = new Test()
test?.sum(2,3)
Run Code Online (Sandbox Code Playgroud)

我必须使用System.out.println该方法,否则会得到StackOverflowError。为什么?

更新:感谢@Dan Getz提供的以下答案,我知道为什么GroovyInterceptable现在该类会发生这种情况。有谁知道Groovy中是否还有其他类实现可能会出现此问题?

Dan*_*etz 5

这是因为您的类Test实现了GroovyInterceptable接口,根据文档,该接口是

用于通知应通过的invokeMethod机制拦截所有方法GroovyObject

这不仅仅是在类中定义的方法。尝试:

test?.total(2,3)
Run Code Online (Sandbox Code Playgroud)

您会看到它返回

用args调用方法总数:[2,3]

因此,对printlninside 的调用应invokeMethod理解为对的调用this.println,就像to的调用一样sum。但是this.println只是invokeMethod再次调用,因为您已实现GroovyInterceptable,依此类推。

如果您没有实现,就不会发生这种情况GroovyInterceptable。例如,运行以下代码

class Test {
    def sum(Integer x, Integer y) { 
        println "Let's sum!"
        x + y
    }
}

def test = new Test()
test?.sum(2,3)
Run Code Online (Sandbox Code Playgroud)

将输出

总结一下!