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