【Groovy】闭包 Closure ( 闭包中调用 Groovy 脚本中的方法 | owner 与 delegate 区别 | 闭包中调用对象中的方法 )
生活随笔
收集整理的這篇文章主要介紹了
【Groovy】闭包 Closure ( 闭包中调用 Groovy 脚本中的方法 | owner 与 delegate 区别 | 闭包中调用对象中的方法 )
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 一、閉包中調用 Groovy 腳本中的方法
- 二、owner 與 delegate 區別
- 三、閉包中調用 Groovy 對象中的方法
一、閉包中調用 Groovy 腳本中的方法
在 Groovy 腳本中 , 在 Closure 閉包中 , 可以直接調用 Groovy 腳本中定義的方法 ;
def fun() {println "fun" }def closure = {fun() }closure()執行上述 Groovy 腳本結果如下 :
fun二、owner 與 delegate 區別
在 Closure 閉包中 , 其 owner 就是創建閉包時所在的環境 , 這是無法改變的 ;
但是 Closure 閉包對象的 delegate 成員是可以修改的 ;
三、閉包中調用 Groovy 對象中的方法
在閉包中 , 可以直接調用 Groovy 腳本中定義的方法 ;
但是如果想要在閉包中 , 調用實例對象的方法 , 就必須設置閉包的 delegate 成員 ;
如下代碼中 , 想要在閉包中 , 調用 Test 對象的 fun 方法 , 在執行閉包之前 , 必須將 閉包的 delegate 設置為 Test 實例對象 ;
closure.delegate = new Test()之后使用
closure()調用閉包 , 在閉包中執行 fun 方法 , 就會在代理 delegate 成員 , 即 Test 實例對象中 , 查找 fun 方法 ;
代碼示例 :
class Test {def fun() {println "fun"} }// 閉包中不能直接調用 Test 對象中的方法 // 此時可以通過改變閉包代理進行調用 def closure = {fun() }closure.delegate = new Test() closure()執行結果 :
fun總結
以上是生活随笔為你收集整理的【Groovy】闭包 Closure ( 闭包中调用 Groovy 脚本中的方法 | owner 与 delegate 区别 | 闭包中调用对象中的方法 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【错误记录】Groovy 闭包使用报错
- 下一篇: 【Groovy】闭包 Closure (