- 閉包定義與調(diào)用
//默認(rèn)參數(shù) it
Closure c = {
it+5
}
//顯式命名參數(shù),此時(shí)就沒有it
Closure d = { k ->
k+5
}
//閉包的調(diào)用
c.call(7)
*動(dòng)態(tài)閉包
def f(Closure closure){
//根據(jù)閉包的參數(shù)的個(gè)數(shù)執(zhí)行不同的邏輯
if (closure.maximumNumberOfParameters == 2){}
else{}
for (param in closure.parameterTypes){
param.name //參數(shù)的類型
}
}
//不同參個(gè)數(shù)的閉包調(diào)用的內(nèi)部邏輯是不一樣的
f{ param1 -> }
f{ param1,param2 -> }
- this、owner、delegate
閉包里面有3個(gè)重要的對(duì)象,把它們弄清楚了,才能對(duì)一些代碼有全面的理解
this:創(chuàng)建閉包的對(duì)象(上下文)
owner:如果閉包在另外一個(gè)閉包中創(chuàng)建,owner指向另一個(gè)的閉包,否則指向this
delegate:默認(rèn)指向owner,但可以設(shè)置為其他對(duì)象
閉包里面的屬性和方法調(diào)用與三個(gè)對(duì)象有密切的關(guān)系,閉包中有個(gè)resolveStrategy,默認(rèn)值為0
public static final int OWNER_FIRST = 0;
public static final int DELEGATE_FIRST = 1;
public static final int OWNER_ONLY = 2;
public static final int DELEGATE_ONLY = 3;
屬性或者方法調(diào)用的查找順序
OWNER_FIRST:
own -> this -> delegate
DELEGATE_FIRST
delegate->own -> this
class Hello {
// def a = "hello a"
def innerC
def c = {
// def a = "closure a"
innerC = {
println(a)
}
delegate = new Delegate()
//修改閉包的delegate
innerC.delegate = delegate
//設(shè)置閉包的代理策略
innerC.setResolveStrategy(Closure.OWNER_FIRST)
innerC.call()
}
def f(){
c.call()
}
}
class Delegate {
def a = "delegate a"
}