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

【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 @Mixin 注解进行方法注入 | Mixin 混合多个类优先级分析 )

作者头像
韩曙亮
发布2023-03-30 11:01:00
8400
发布2023-03-30 11:01:00
举报
文章被收录于专栏:韩曙亮的移动开发专栏

文章目录

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


在上一篇博客 【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 Mixin 混合进行方法注入 ) 中 , 使用了

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

代码 , 将两个类进行混合 , 可以使用 @Mixin 注解 , 混合两个类 ,

代码语言:javascript
复制
@Mixin(Hello)
class Student {
    def name
}

上述两种操作是等效的 , 代码示例 :

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

执行结果 :

代码语言:javascript
复制
Hello Tom

二、Mixin 混合多个类优先级分析


如果定义了

2

个注入方法类 , 其中都定义了 hello 方法 ,

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

// 定义被注入的方法2
class Hello2 {
    def hello (Student student) {
        println "Hello2 ${student.name}"
    }
}

调用类的 mixin 方法 , 同时注入两个类 , 调用方法时 , 从右侧的注入类开始查找对应的注入方法 ;

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

上述注入的方法类 , 先查找 Hello2 中是否有 hello 方法 , 如果有直接使用 , Hello 类中的 hello 方法被屏蔽了 ;

在下面的代码中 , 执行 Student 对象的 hello 方法 , 执行的是 Hello2#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}"
    }
}

// 定义被注入的方法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)

执行结果 :

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 一、使用 Mixin 混合进行方法注入
  • 二、Mixin 混合多个类优先级分析
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档