【Groovy】MOP 元对象协议与元编程 ( 使用 Groovy 元编程进行函数拦截 | 动态拦截函数 | 动态获取 MetaClass 中的方法 | evaluate 方法执行Groovy脚本 )
生活随笔
收集整理的這篇文章主要介紹了
【Groovy】MOP 元对象协议与元编程 ( 使用 Groovy 元编程进行函数拦截 | 动态拦截函数 | 动态获取 MetaClass 中的方法 | evaluate 方法执行Groovy脚本 )
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 一、基礎示例
- 二、根據字符串動態獲取 MetaClass 中的方法
- 二、使用 evaluate 執行字符串形式的 Groovy 腳本
- 二、完整代碼示例
一、基礎示例
定義類 Student , 在其中聲明若干成員變量和成員方法 ;
class Student {def namedef agedef hello() {println "Hello , my name is $name, $age years old"}def walk() {println "$name walk"} }初始化 Student 對象 , 并執行 Student 對象的 hello 方法 ,
def student = new Student(name: "Tom", age: 18)// 第一次調用 hello 方法 student.hello()執行結果如下 :
Hello , my name is Tom, 18 years old二、根據字符串動態獲取 MetaClass 中的方法
進行動態函數攔截時 , 事先不知道要要攔截的方法名 , 這里聲明一個藥攔截的方法名變量 ;
// 要攔截的方法名 def interceptMethodName = "hello"使用如下代碼操作 , 即可獲取 MetaClass 中的方法 ;
// 函數攔截操作 student.metaClass."${interceptMethodName}"二、使用 evaluate 執行字符串形式的 Groovy 腳本
動態函數攔截時 , 也不知道攔截后要執行哪些操作 , 使用 evaluate 函數 , 可以直接執行的 Groovy 腳本字符串 ;
Groovy 腳本字符串如下 :
// 攔截后要執行的 字符串 代碼 def interceptAction = "println 'Intercept Hello Method'"執行 Groovy 腳本字符串 :
// 執行 代碼 , 傳入的參數是 代碼的字符串形式evaluate(interceptAction)代碼示例 :
// 要攔截的方法名 def interceptMethodName = "hello"// 攔截后要執行的 字符串 代碼 def interceptAction = "println 'Intercept Hello Method'"// 函數攔截操作 student.metaClass."${interceptMethodName}" = {// 執行 代碼 , 傳入的參數是 代碼的字符串形式evaluate(interceptAction) }二、完整代碼示例
完整代碼示例 : 在下面的代碼中 , 先執行原始的 hello 方法 ; 然后第一次動態攔截 hello 方法 , 執行 "println 'Intercept Hello Method'" 字符串腳本內容 , 再次執行 hello 方法 ; 最后再次動態攔截 hello 方法 , 執行 "println 'Intercept Hello Method Second Time'" 字符串腳本內容 , 執行 hello 方法 ;
class Student {def namedef agedef hello() {println "Hello , my name is $name, $age years old"}def walk() {println "$name walk"} }def student = new Student(name: "Tom", age: 18)// 第一次調用 hello 方法 student.hello()// I. 第一次進行函數攔截// 要攔截的方法名 def interceptMethodName = "hello"// 攔截后要執行的 字符串 代碼 def interceptAction = "println 'Intercept Hello Method'"// 函數攔截操作 student.metaClass."${interceptMethodName}" = {// 執行 代碼 , 傳入的參數是 代碼的字符串形式evaluate(interceptAction) }// 方法攔截后執行 hello 方法 student.hello()// II . 第二次進行函數攔截// 攔截后要執行的 字符串 代碼 interceptAction = "println 'Intercept Hello Method Second Time'"// 函數攔截操作 student.metaClass."${interceptMethodName}" = {// 執行 代碼 , 傳入的參數是 代碼的字符串形式evaluate(interceptAction) }// 方法攔截后執行 hello 方法 student.hello()執行結果 :
Hello , my name is Tom, 18 years old Intercept Hello Method Intercept Hello Method Second Time總結
以上是生活随笔為你收集整理的【Groovy】MOP 元对象协议与元编程 ( 使用 Groovy 元编程进行函数拦截 | 动态拦截函数 | 动态获取 MetaClass 中的方法 | evaluate 方法执行Groovy脚本 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Groovy】MOP 元对象协议与元编
- 下一篇: 【Groovy】MOP 元对象协议与元编