【Groovy】MOP 元对象协议与元编程 ( 方法合成 | 动态注入方法 )
生活随笔
收集整理的这篇文章主要介绍了
【Groovy】MOP 元对象协议与元编程 ( 方法合成 | 动态注入方法 )
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
文章目录
- 一、动态注入方法
- 二、完整代码示例
一、动态注入方法
调用 Student 类不存在的方法 , 如果该类重写了
def methodMissing(String name, def args)方法 , 就会回调该函数 , 并且可以从参数中拿到方法名和参数列表 ;
在 methodMissing 方法中 , 可以动态注入该不存在的函数 ;
首先 , 获取 org.codehaus.groovy.runtime.HandleMetaClass 类 , 先将 this 赋值给 Student 对象 , 然后通过 Student 对象获取 metaClass ;
// 先将 this 赋值给 Student 对象// 然后通过 Student 对象获取 metaClassStudent student = thisprintln student.metaClass然后 , 根据方法名称 , 动态注入方法 ; 使用 student.metaClass."方法名" = {闭包} 代码进行方法注入 , 注册前 , 不知道方法名称 , 运行时动态确定注入的方法名 ;
println "动态注入 ${name} 方法, 开始注入!"// 动态注入方法student.metaClass."${name}" = {println "执行动态注入 ${name} 方法, 执行相关操作!"}println "动态注入 ${name} 方法, 注入完毕!"最后 , 方法注入之后 , 使用 "方法名"(参数列表) 代码调用注入的方法 , 只需要知道方法名就可以调用该方法 ;
// 调用上述动态注入的方法// 注意这里传入的参数, 可以直接传入闭包中"$name"(args)二、完整代码示例
完整代码示例 :
class Student {def methodMissing(String name, def args) {// 直接获取 metaClassprintln metaClass// 先将 this 赋值给 Student 对象// 然后通过 Student 对象获取 metaClassStudent student = thisprintln student.metaClassprintln "动态注入 ${name} 方法, 开始注入!"// 动态注入方法student.metaClass."$name" = {println "执行动态注入 ${name} 方法, 执行相关操作!"}println "动态注入 ${name} 方法, 注入完毕!"// 调用上述动态注入的方法// 注意这里传入的参数, 可以直接传入闭包中"$name"(args)return null} }def student = new Student()// 第一次调用 hello 方法 , 方法没有注入 , 先注入再执行 student.hello() // 第二次调用hello 方法 , 方法之前注入过了 , 可以直接调用 student.hello()执行结果 :
第一次调用 : groovy.lang.MetaClassImpl@3e3047e6[class Student] org.codehaus.groovy.runtime.HandleMetaClass@3e3047e6[groovy.lang.MetaClassImpl@3e3047e6[class Student]] 动态注入 hello 方法, 开始注入! 动态注入 hello 方法, 注入完毕! 执行动态注入 hello 方法, 执行相关操作! 第二次调用 : 执行动态注入 hello 方法, 执行相关操作!总结
以上是生活随笔为你收集整理的【Groovy】MOP 元对象协议与元编程 ( 方法合成 | 动态注入方法 )的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 【Groovy】MOP 元对象协议与元编
- 下一篇: 【错误记录】IntelliJ IDEA