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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

【Groovy】MOP 元对象协议与元编程 ( 使用 Groovy 元编程进行函数拦截 | 重写 MetaClass#invokeMethod 方法实现函数拦截 | 实现函数调用转发 )

發布時間:2025/6/17 编程问答 19 豆豆

文章目錄

  • 一、重寫 MetaClass#invokeMethod 方法實現函數攔截
  • 二、在 MetaClass#invokeMethod 方法中調用對象的其它方法
  • 三、完整代碼示例





一、重寫 MetaClass#invokeMethod 方法實現函數攔截



在 Groovy 中 , 如果覆蓋了對象的 MetaClass#invokeMethod 方法 , 那么 , 在執行該對象的任何方法時 , 都會回調該 invokeMethod 方法 ;

給定一個類和該類的實例對象 :

class Student{def name;def hello() {System.out.println "Hello ${name}"} }def student = new Student(name: "Tom")

覆蓋 student.metaClass 的 invokeMethod 方法 ,

// 如果覆蓋了 invokeMethod 方法 // 那么 , 執行該對象的任何方法時 , 都會回調該 invokeMethod 方法 student.metaClass.invokeMethod = {String name, Object args ->System.out.println "invokeMethod : String name : $name , Object args : $args" }

調用 student 對象的 hello 方法時 , 就會回調該閉包中的方法 , 即使沒有實現 GroovyInterceptable 接口 , 也可以進行函數攔截 ;





二、在 MetaClass#invokeMethod 方法中調用對象的其它方法



使用

student.metaClass.invokeMethod = {}

重寫了 invokeMethod 方法后 , 攔截函數之后 , 需要將方法傳遞下去 , 調用真正要調用的方法 ;

注意此處不能使用 student.metaClass.invokeMethod 調用其它方法 , 這樣會導致無限循環遞歸調用 , 導致棧溢出異常 ;


MetaClass#invokeMethod 方法中調用對象的其它方法 ,

  • 首先 , 要從 student.metaClass 中根據 方法名 和 方法參數 獲取指定的 MetaMethod ;
// 方法轉發 : 調用 student 對象中的原來的方法// 注意此處不能使用 metaClass.invokeMethod 方法調用對象中的方法 , 會導致棧溢出// 這里通過 MetaClass#getMetaMethod 獲取方法 , 然后執行def method = student.metaClass.getMetaMethod(name, args)
  • 然后 , 執行該 MetaMethod 方法 , 需要傳入 對象 和 參數 ;
// 方法不為空再執行該方法if (method != null) {method.invoke(student, args)}



三、完整代碼示例



完整代碼示例 :

class Student{def name;def hello() {System.out.println "Hello ${name}"} }def student = new Student(name: "Tom") def student2 = new Student(name: "Jerry")// 如果覆蓋了 invokeMethod 方法 // 那么 , 執行該對象的任何方法時 , 都會回調該 invokeMethod 方法 student.metaClass.invokeMethod = {String name, Object args ->System.out.println "invokeMethod : String name : $name , Object args : $args"// 方法轉發 : 調用 student 對象中的原來的方法// 注意此處不能使用 metaClass.invokeMethod 方法調用對象中的方法 , 會導致棧溢出// 這里通過 MetaClass#getMetaMethod 獲取方法 , 然后執行def method = student.metaClass.getMetaMethod(name, args)// 方法不為空再執行該方法if (method != null) {method.invoke(student, args)} }// 直接調用 hello 方法 student.hello() student2.hello()

執行結果 :

invokeMethod : String name : hello , Object args : [] Hello Tom Hello Jerry

總結

以上是生活随笔為你收集整理的【Groovy】MOP 元对象协议与元编程 ( 使用 Groovy 元编程进行函数拦截 | 重写 MetaClass#invokeMethod 方法实现函数拦截 | 实现函数调用转发 )的全部內容,希望文章能夠幫你解決所遇到的問題。

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