Groovy解惑 closure中的owner

2021-04-19 23:06:49 字數 2099 閱讀 3558

groovy解惑——closure中的owner

在上篇《

groovy解惑——closure中的delegate

》中,我幫大家講解了delegate是什麼以及其作用。

本篇將講解一下closure中的owner,以及this,delegate以及owner三者間的關係。

先讓我們來看個例子:

class

ownerdemo 

innestclosure()

}innerclosure()}}

def ownerdemo 

=new

ownerdemo()

ownerdemo.outerclosure()

執行結果:

the owner of outerclosure: ownerdemo@eccfe7

the owner of innerclosure: ownerdemo$_closure1@4745cf

the owner of innestclosure: ownerdemo$_closure1_closure2@109dcbb

注意:ownerdemo$_closure1指的是outerclosure的類名,而ownerdemo$_closure1_closure2指的是innerclosure的類名

通過這個例子,大家就清楚了,closure的owner引用的是該closure的『擁有者』

那麼this, delegate以及owner有什麼關係呢?

隱式變數delegate的預設值為owner,

如果closure沒有『巢狀』在其他closure中,那麼該closure的owner的值為this;

否則該closure的owner引用的是『直接包含』該closure的closure

讓我們用事實來說話吧:

class

ownerdemo 

println 

"innestclosure: "+

innestclosure

innestclosure()

}println 

"innerclosure: "+

innerclosure

innerclosure()}}

def ownerdemo 

=new

ownerdemo()

def outerclosure 

=ownerdemo.outerclosure

println 

"outerclosure: "+

outerclosure

outerclosure()

執行結果:

outerclosure: ownerdemo$_closure1@10cc9b4

the owner of outerclosure: ownerdemo@8e7f54

the delegate of outerclosure: ownerdemo@8e7f54

this in the outerclosure: ownerdemo@8e7f54

innerclosure: ownerdemo$_closure1_closure2@1eb1db2

the owner of innerclosure: ownerdemo$_closure1@10cc9b4

the delegate of innerclosure: ownerdemo$_closure1@10cc9b4

this in the innerclosure: ownerdemo@8e7f54

innestclosure: ownerdemo$_closure1_closure2_closure3@12a78ee

the owner of innestclosure: ownerdemo$_closure1_closure2@1eb1db2

the delegate of innestclosure: ownerdemo$_closure1_closure2@1eb1db2

this in the innestclosure: ownerdemo@8e7f54

大家可以從其中值的關係看出this, delegate以及owner三者的關係與我們之前所說的相符 :)

』的常客 :)

Groovy集合型別

groovy中有3種集合型別,分別是列表list 對映map 區間range 1 列表 list的初始化,直接在 中直接寫入初始的資料即可 def list1 1,2,3 list支援的運算子和方法 def list2 list1 2 1,2,3,1,2,3 list2.unique 1,2,3 l...

groovy動態語言

import groovy.transform.compilestatic import groovy.transform.typechecked 動態語言測試 typechecked 檢測語法 respondsto 檢測是否實現了某個方法 hasproperty 檢測是否含有某個屬性 compil...

Groovy方法注入

分類注入 1class req use req class stringutil 載入順序右後到先 stringutil req 本身的方法 use req,stringutil println get 給類注入靜態方法 def str string.metaclass.static printcl...