【Groovy】MOP 元对象协议与元编程 ( 方法合成 | 动态注入方法 )
生活随笔
收集整理的這篇文章主要介紹了
【Groovy】MOP 元对象协议与元编程 ( 方法合成 | 动态注入方法 )
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
文章目錄
- 一、動態(tài)注入方法
- 二、完整代碼示例
一、動態(tài)注入方法
調(diào)用 Student 類不存在的方法 , 如果該類重寫了
def methodMissing(String name, def args)方法 , 就會回調(diào)該函數(shù) , 并且可以從參數(shù)中拿到方法名和參數(shù)列表 ;
在 methodMissing 方法中 , 可以動態(tài)注入該不存在的函數(shù) ;
首先 , 獲取 org.codehaus.groovy.runtime.HandleMetaClass 類 , 先將 this 賦值給 Student 對象 , 然后通過 Student 對象獲取 metaClass ;
// 先將 this 賦值給 Student 對象// 然后通過 Student 對象獲取 metaClassStudent student = thisprintln student.metaClass然后 , 根據(jù)方法名稱 , 動態(tài)注入方法 ; 使用 student.metaClass."方法名" = {閉包} 代碼進(jìn)行方法注入 , 注冊前 , 不知道方法名稱 , 運(yùn)行時動態(tài)確定注入的方法名 ;
println "動態(tài)注入 ${name} 方法, 開始注入!"// 動態(tài)注入方法student.metaClass."${name}" = {println "執(zhí)行動態(tài)注入 ${name} 方法, 執(zhí)行相關(guān)操作!"}println "動態(tài)注入 ${name} 方法, 注入完畢!"最后 , 方法注入之后 , 使用 "方法名"(參數(shù)列表) 代碼調(diào)用注入的方法 , 只需要知道方法名就可以調(diào)用該方法 ;
// 調(diào)用上述動態(tài)注入的方法// 注意這里傳入的參數(shù), 可以直接傳入閉包中"$name"(args)二、完整代碼示例
完整代碼示例 :
class Student {def methodMissing(String name, def args) {// 直接獲取 metaClassprintln metaClass// 先將 this 賦值給 Student 對象// 然后通過 Student 對象獲取 metaClassStudent student = thisprintln student.metaClassprintln "動態(tài)注入 ${name} 方法, 開始注入!"// 動態(tài)注入方法student.metaClass."$name" = {println "執(zhí)行動態(tài)注入 ${name} 方法, 執(zhí)行相關(guān)操作!"}println "動態(tài)注入 ${name} 方法, 注入完畢!"// 調(diào)用上述動態(tài)注入的方法// 注意這里傳入的參數(shù), 可以直接傳入閉包中"$name"(args)return null} }def student = new Student()// 第一次調(diào)用 hello 方法 , 方法沒有注入 , 先注入再執(zhí)行 student.hello() // 第二次調(diào)用hello 方法 , 方法之前注入過了 , 可以直接調(diào)用 student.hello()執(zhí)行結(jié)果 :
第一次調(diào)用 : groovy.lang.MetaClassImpl@3e3047e6[class Student] org.codehaus.groovy.runtime.HandleMetaClass@3e3047e6[groovy.lang.MetaClassImpl@3e3047e6[class Student]] 動態(tài)注入 hello 方法, 開始注入! 動態(tài)注入 hello 方法, 注入完畢! 執(zhí)行動態(tài)注入 hello 方法, 執(zhí)行相關(guān)操作! 第二次調(diào)用 : 執(zhí)行動態(tài)注入 hello 方法, 執(zhí)行相關(guān)操作!總結(jié)
以上是生活随笔為你收集整理的【Groovy】MOP 元对象协议与元编程 ( 方法合成 | 动态注入方法 )的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Groovy】MOP 元对象协议与元编
- 下一篇: 【错误记录】IntelliJ IDEA