【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 MetaClass 进行方法注入普通方法 )
生活随笔
收集整理的這篇文章主要介紹了
【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 MetaClass 进行方法注入普通方法 )
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 一、使用 MetaClass 進行方法注入
- 二、完整代碼示例
一、使用 MetaClass 進行方法注入
定義 Student 類 ,
class Student {def name; }為該 Student 類注入一個 hello 方法 , 先獲取 Student 類的 metaClass 成員 , 然后為其注入 hello 方法 , 使用 << 符號 , 后面帶上一個閉包 , 即可注入方法 , 在閉包中 , delegate 就是 Student 對象 ;
// 向 Student 類注入 hello 方法 Student.metaClass.hello << {println delegateprintln "Hello ${delegate.name}" }創建 Student 實例對象 , 調用為 Student 類注入的 hello 方法 ,
def student = new Student(name: "Tom") student.hello()即可打印出
Student@5dd6264 Hello Tom內容 , 其中 Student@5dd6264 是 MetaClass 中的 delegate 代理對象 ;
此處注意 , 注入方法使用 << 運算符 , 替換 / 攔截方法 使用 = 運算符 ;
方法注入后 , 在 類 的 metaClass 中注入的方法 , 在任何 Student 對象中 , 都可以調用被注入的 hello 方法 ;
但是在 對象 的 metaClass 中注入的方法 , 只有該 Student 對象才能調用被注入的 hello 方法 , 其它對象不能調用該注入的方法 ;
二、完整代碼示例
完整代碼示例 :
class Student {def name; }// 向 Student 類注入 hello 方法 Student.metaClass.hello << {println delegateprintln "Hello ${delegate.name}" }/*注入方法使用 <<替換 / 攔截方法 使用 =*/def student = new Student(name: "Tom") student.hello()執行結果 :
Student@5dd6264 Hello Tom總結
以上是生活随笔為你收集整理的【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 MetaClass 进行方法注入普通方法 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Groovy】MOP 元对象协议与元编
- 下一篇: 【错误记录】Groovy 注入方法报错