【Groovy】MOP 元对象协议与元编程 ( 使用 Groovy 元编程进行函数拦截 | 重写 MetaClass#invokeMethod 方法实现函数拦截 | 实现函数调用转发 )
生活随笔
收集整理的這篇文章主要介紹了
【Groovy】MOP 元对象协议与元编程 ( 使用 Groovy 元编程进行函数拦截 | 重写 MetaClass#invokeMethod 方法实现函数拦截 | 实现函数调用转发 )
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 一、重寫 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 ;
- 然后 , 執行該 MetaMethod 方法 , 需要傳入 對象 和 參數 ;
三、完整代碼示例
完整代碼示例 :
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 方法实现函数拦截 | 实现函数调用转发 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Groovy】MOP 元对象协议与元编
- 下一篇: 【Groovy】MOP 元对象协议与元编