【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 Mixin 混合进行方法注入 )
2023-09-14 09:07:28 时间
一、使用 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
相关文章
- 两列布局之左边固定宽度,右边自适应(绝对定位实现方法)
- 【Mysql sql inject】POST方法BASE64编码注入write-up
- Windows 7环境下HttpListener拒绝访问异常解决方法
- PHP+Mysql防止SQL注入的方法
- SpringBoot中Junit测试注入Bean失败的解决方法
- [JavaME]利用java.util.TimerTask来做Splash Screen的N种方法
- Debian下配置SSH服务器的方法
- TS - 解决问题的一些方法
- 怎么用命令激活win10教育版|win10教育版命令激活方法
- Xml 常用属性、方法
- 在javascript中重新加载/刷新页面的不同方法
- Android 添加系统服务的方法详解
- DL之Transformer:Transformer的简介(优缺点/架构详解,基于Transformer的系列架构对比分析)、使用方法(NLP领域/CV领域)、案例应用之详细攻略
- Graphviz:可视化工具Graphviz的简介、安装、使用方法、经典案例之详细攻略
- LTE CSFB失败原因及优化方法
- 【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 同时注入普通方法、静态方法、构造方法 )
- 【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 @Category 注解进行方法注入 | 分类注入方法查找优先级 )
- 64位程序调用32位dll的方法
- Mysql下Limit注入方法(此方法仅适用于5.0.0<mysql<5.6.6的版本)
- python调用外部可执行文件的三种方法
- monkey源代码分析之事件注入方法变化
- centos 安装docker方法2
- 【.Net实用方法总结】 整理并总结System.IO中Path类及其方法介绍