【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 Mixin 混合进行方法注入 )
生活随笔
收集整理的這篇文章主要介紹了
【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 Mixin 混合进行方法注入 )
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 一、使用 Mixin 混合進行方法注入
- 二、完整代碼示例
一、使用 Mixin 混合進行方法注入
使用 Mixin 混合進行方法注入 , 為下面的 Student 類注入方法 ;
class Student {def name }首先 , 定義被注入的方法 , 定義一個類 , 在類中定義被注入的方法 , 這里需要注意 , 被注入的方法沒有 self 參數 , 不能訪問其本身對象 , 如果需要訪問本身 , 需要通過參數傳遞進去 ;
// 定義被注入的方法 class Hello {def hello (Student student) {println "Hello ${student.name}"} }然后 , 調用類的 mixin 方法 , 將注入方法所在的類混合進指定的 需要注入方法 的類中 ; 可以直接向 Student 類中混合 , 也可以像 Student.metaClass 中混合 , 二者效果相同 ;
// 將 Hello 類中的方法注入到 Student 類中 Student.mixin(Hello)最后 , 直接調用被注入的方法 , 這里要注意 , 使用 Student 對象調用 hello 方法時 , 同時需要在參數中 , 也傳遞一個該對象 ;
// 創建 Student 對象 def student = new Student(name: "Tom")// 調用被注入的方法 student.hello(student)二、完整代碼示例
完整代碼示例 :
class Student {def name }// 定義被注入的方法 class Hello {def hello (Student student) {println "Hello ${student.name}"} }// 將 Hello 類中的方法注入到 Student 類中 Student.mixin(Hello)// 創建 Student 對象 def student = new Student(name: "Tom")// 調用被注入的方法 student.hello(student)執行結果 :
Hello Tom總結
以上是生活随笔為你收集整理的【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 Mixin 混合进行方法注入 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【错误记录】IntelliJ IDEA
- 下一篇: 【Groovy】MOP 元对象协议与元编