简体   繁体   English

试图了解Groovy中的运行时关闭/方法覆盖

[英]Trying to understand runtime closure/method overwriting in Groovy

I wrote the following code to learn closure/method overwriting in groovy. 我编写了以下代码,以学习groovy中的闭包/方法覆盖。 I couldn't understand its behavior. 我无法理解它的行为。

class AClass {
    def closure1 = { ->  println "hello from closure1 - ${this.toString()}" }

    def closure2 = { c1 ->
        print "closure2 { \n    "
        c1()
        println "}"
    }
}

def obj = new AClass()
print "1: "
obj.closure1()

//over write closure1
obj.metaClass.closure1 = { -> println "hello from *** overridden closure1 *** - ${this.toString()}".toUpperCase()}
print "\n2: "
obj.closure1() //To confirm closure1 was indeed overwritten

//call closure2
print "\n3: "
obj.closure2 (obj.closure1)
print "\n4: "
obj.closure2 {obj.closure1()}

I was expecting the two closure2 calls to generate the same result but apparently they don't. 我原以为两个closure2调用会产生相同的结果,但显然它们不会。

Below is the result of running my code. 以下是运行我的代码的结果。

1: hello from closure1 - AClass@d706f19

2: HELLO FROM *** OVERRIDDEN CLOSURE1 *** - TESTMTDOVERRIDE@BE64738

3: closure2 { 
    hello from closure1 - AClass@d706f19
}

4: closure2 { 
    HELLO FROM *** OVERRIDDEN CLOSURE1 *** - TESTMTDOVERRIDE@BE64738
}

You have two different things here... A variable closure1 that holds a closure, and a method closure1 which you have added to the metaClass via a closure... 您在这里有两种不同的选择:一个变量closure1持有一个闭包,以及方法closure1 ,您已通过一个闭包将其添加到metaClass中。

obj.closure2 (obj.closure1)

Calls closure2, and passes in the variable 调用closure2,并传入变量

obj.closure2 {obj.closure1()}

Passes a closure that calls the closure in the metaClass 传递一个闭包,该闭包在metaClass中调用

They are very different things 他们是完全不同的东西

You've just called them the same 你刚刚给他们打电话了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM