【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 MetaClass 注入静态方法 )
生活随笔
收集整理的這篇文章主要介紹了
【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 MetaClass 注入静态方法 )
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 一、使用 MetaClass 注入靜態方法
- 二、完整代碼示例
一、使用 MetaClass 注入靜態方法
使用 MetaClass 注入靜態方法 , 可以使用如下代碼實現 :
類名.metaClass.'static'.被注入的靜態方法名 = { 閉包 }定義 Student 類 , 其中定義 name 成員 ;
class Student {def name; }使用上述語法 , 向 Student 類注入 hello 靜態方法 ;
// 向 Student 類注入 hello 靜態方法 Student.metaClass.'static'.hello = {println "Hello Student ${delegate.name}" }注意這里在 被注入的 hello 靜態方法中 , 使用了 delegate ,
- 如果使用 Student 類調用 hello 方法 , 則 delegate 就是 Student 類 ;
- 如果使用 Student 對象調用 hello 方法 , 則 delegate 就是 Student 對象 ;
二、完整代碼示例
完整代碼示例 :
class Student {def name; }// 向 Student 類注入 hello 方法 Student.metaClass.'static'.hello = {println "Hello Student ${delegate.name}" }// 通過 Student 類調用靜態方法 Student.hello()// 通過 Student 對象調用靜態方法 def student = new Student(name: "Tom") student.hello()執行結果 :
Hello Student Student Hello Student Tom總結
以上是生活随笔為你收集整理的【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 MetaClass 注入静态方法 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【错误记录】Groovy 注入方法报错
- 下一篇: 【Groovy】MOP 元对象协议与元编