Groovy閉包

  • 閉包定義與調(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"
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容