日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【Groovy】闭包 Closure ( 闭包调用 与 call 方法关联 | 接口中定义 call() 方法 | 类中定义 call() 方法 | 代码示例 )

發布時間:2025/6/17 编程问答 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【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() 方法 | 代码示例 )的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。