试图理解Groovy

时间:2017-09-08 17:16:35

标签: groovy metaclass method-overriding

我编写了以下代码来学习groovy中的闭包/方法覆盖。我无法理解它的行为。

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()}

我期待两次closure2次调用产生相同的结果,但显然他们没有。

以下是运行我的代码的结果。

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
}

1 个答案:

答案 0 :(得分:0)

这里有两个不同的东西......一个包含闭包的变量closure1和一个通过闭包添加到metaClass的方法closure1 ...

obj.closure2 (obj.closure1)

调用closure2,并传入变量

obj.closure2 {obj.closure1()}

传递一个在metaClass中调用闭包的闭包

他们是非常不同的东西

你刚才称他们为同一个