前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 Mixin 混合进行方法注入 )

【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 Mixin 混合进行方法注入 )

作者头像
韩曙亮
发布2023-03-30 11:00:04
2010
发布2023-03-30 11:00:04
举报

文章目录

一、使用 Mixin 混合进行方法注入


使用 Mixin 混合进行方法注入 , 为下面的 Student 类注入方法 ;

代码语言:javascript
复制
class Student {
    def name
}

首先 , 定义被注入的方法 , 定义一个类 , 在类中定义被注入的方法 , 这里需要注意 , 被注入的方法没有 self 参数 , 不能访问其本身对象 , 如果需要访问本身 , 需要通过参数传递进去 ;

代码语言:javascript
复制
// 定义被注入的方法
class Hello {
    def hello (Student student) {
        println "Hello ${student.name}"
    }
}

然后 , 调用类的 mixin 方法 , 将注入方法所在的类混合进指定的 需要注入方法 的类中 ; 可以直接向 Student 类中混合 , 也可以像 Student.metaClass 中混合 , 二者效果相同 ;

代码语言:javascript
复制
// 将 Hello 类中的方法注入到 Student 类中
Student.mixin(Hello)

最后 , 直接调用被注入的方法 , 这里要注意 , 使用 Student 对象调用 hello 方法时 , 同时需要在参数中 , 也传递一个该对象 ;

代码语言:javascript
复制
// 创建 Student 对象
def student = new Student(name: "Tom")

// 调用被注入的方法
student.hello(student)

二、完整代码示例


完整代码示例 :

代码语言:javascript
复制
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)

执行结果 :

代码语言:javascript
复制
Hello Tom
在这里插入图片描述
在这里插入图片描述
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-01-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 一、使用 Mixin 混合进行方法注入
  • 二、完整代码示例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档