【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 @Mixin 注解进行方法注入 | Mixin 混合多个类优先级分析 )
生活随笔
收集整理的這篇文章主要介紹了
【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 @Mixin 注解进行方法注入 | Mixin 混合多个类优先级分析 )
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 一、使用 Mixin 混合進行方法注入
- 二、Mixin 混合多個類優先級分析
一、使用 Mixin 混合進行方法注入
在上一篇博客 【Groovy】MOP 元對象協議與元編程 ( 方法注入 | 使用 Mixin 混合進行方法注入 ) 中 , 使用了
// 將 Hello 類中的方法注入到 Student 類中 Student.mixin(Hello)代碼 , 將兩個類進行混合 , 可以使用 @Mixin 注解 , 混合兩個類 ,
@Mixin(Hello) class Student {def name }上述兩種操作是等效的 , 代碼示例 :
@Mixin(Hello) 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二、Mixin 混合多個類優先級分析
如果定義了 222 個注入方法類 , 其中都定義了 hello 方法 ,
// 定義被注入的方法 class Hello {def hello (Student student) {println "Hello ${student.name}"} }// 定義被注入的方法2 class Hello2 {def hello (Student student) {println "Hello2 ${student.name}"} }調用類的 mixin 方法 , 同時注入兩個類 , 調用方法時 , 從右側的注入類開始查找對應的注入方法 ;
// 將 Hello 類中的方法注入到 Student 類中 Student.mixin(Hello, Hello2)上述注入的方法類 , 先查找 Hello2 中是否有 hello 方法 , 如果有直接使用 , Hello 類中的 hello 方法被屏蔽了 ;
在下面的代碼中 , 執行 Student 對象的 hello 方法 , 執行的是 Hello2#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}"} }// 定義被注入的方法2 class Hello2 {def hello (Student student) {println "Hello2 ${student.name}"} }// 將 Hello 類中的方法注入到 Student 類中 Student.mixin(Hello, Hello2)// 創建 Student 對象 def student = new Student(name: "Tom")// 調用被注入的方法 student.hello(student)執行結果 :
Hello2 Tom總結
以上是生活随笔為你收集整理的【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 @Mixin 注解进行方法注入 | Mixin 混合多个类优先级分析 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Groovy】MOP 元对象协议与元编
- 下一篇: 【Groovy】MOP 元对象协议与元编