【Groovy】闭包 Closure ( 闭包调用 与 call 方法关联 | 接口中定义 call() 方法 | 类中定义 call() 方法 | 代码示例 )
生活随笔
收集整理的這篇文章主要介紹了
【Groovy】闭包 Closure ( 闭包调用 与 call 方法关联 | 接口中定义 call() 方法 | 类中定义 call() 方法 | 代码示例 )
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 總結
- 一、接口中定義 call() 方法
- 二、類中定義 call() 方法
- 三、完整代碼示例
總結
在 實例對象后使用 " () " 括號符號 , 表示調用該實例對象的 " call() " 方法 ;
一、接口中定義 call() 方法
定義 Action 接口 , 在該接口中 , 創建 void call() 抽象方法 ;
/*** 創建接口* 接口中定義 call 方法* 調用上述 接收 閉包作為參數的 fun 函數時* 傳入該 Action 匿名內部類*/ interface Action {void call() }創建上述 Action 方法的匿名內部類 , 并 使用 () 執行上述匿名內部類對象 , 會 自動調用 Action 匿名內部類的 call 方法 ;
// 在 Action 對象后使用 () 執行方法相當于調用 call 方法 new Action(){@Overridevoid call() {println "Closure 3"} }()執行上述代碼 , 會打印
Closure 3內容 ;
同時上述匿名內部類 , 可以當做閉包 , 傳遞給
/*** 定義一個方法 , 接收閉包作為參數 , 在方法中執行閉包內容* @param closure* @return*/ def fun(closure) {closure() }函數 ; 向 fun 函數中 , 傳入 Action 匿名內部類 , 此時執行該函數時 , 執行閉包內容 , 會自動調用 Action 匿名內部類的 call 方法 ;
// 向 fun 函數中 , 傳入 Action 匿名內部類 // 此時執行該函數時 , 執行閉包內容 , 會自動調用 Action 匿名內部類的 call 方法 fun (new Action(){@Overridevoid call() {println "Closure 3"} })上述 fun 函數的執行結果 :
Closure 4二、類中定義 call() 方法
在普通的 Groovy 類中 , 定義 call() 方法 ;
// 定義一個有 call 方法的類 class Action2 {def call() {println "Closure 5"} }在該類實例對象后 使用 () , 會自動執行該類的 call 方法 ;
// 在該類實例對象后使用 () , 會自動執行該類的 call 方法 new Action2()()執行結果為 :
Closure 5三、完整代碼示例
完整代碼示例 :
/*** 定義一個方法 , 接收閉包作為參數 , 在方法中執行閉包內容* @param closure* @return*/ def fun(closure) {closure() }/*** 創建接口* 接口中定義 call 方法* 調用上述 接收 閉包作為參數的 fun 函數時* 傳入該 Action 匿名內部類*/ interface Action {void call() }// 將 閉包 當做 參數 傳遞到函數中 fun ({println "Closure 1" })// 閉包是函數的最后一個參數 , 可以 省略括號 , 將閉包寫在函數后面 fun {println "Closure 2" }// 在 Action 對象后使用 () 執行方法相當于調用 call 方法 new Action(){@Overridevoid call() {println "Closure 3"} }()// 向 fun 函數中 , 傳入 Action 匿名內部類 // 此時執行該函數時 , 執行閉包內容 , 會自動調用 Action 匿名內部類的 call 方法 fun (new Action(){@Overridevoid call() {println "Closure 4"} })// 定義一個有 call 方法的類 class Action2 {def call() {println "Closure 5"} }// 在該類實例對象后使用 () , 會自動執行該類的 call 方法 new Action2()()執行結果 :
Closure 1 Closure 2 Closure 3 Closure 4 Closure 5總結
以上是生活随笔為你收集整理的【Groovy】闭包 Closure ( 闭包调用 与 call 方法关联 | 接口中定义 call() 方法 | 类中定义 call() 方法 | 代码示例 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Groovy】闭包 Closure (
- 下一篇: 【Groovy】闭包 Closure (