欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

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

发布时间:2025/6/17 48 豆豆
生活随笔 收集整理的这篇文章主要介绍了 【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 @Mixin 注解进行方法注入 | Mixin 混合多个类优先级分析 ) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

文章目录

  • 一、使用 Mixin 混合进行方法注入
  • 二、Mixin 混合多个类优先级分析





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



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

// 将 Hello 类中的方法注入到 Student 类中 Student.mixin(Hello)

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

@Mixin(Hello) class Student {def name }

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

@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)

执行结果 :

Hello Tom



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



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

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

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

// 将 Hello 类中的方法注入到 Student 类中 Student.mixin(Hello, Hello2)

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

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

执行结果 :

Hello2 Tom

总结

以上是生活随笔为你收集整理的【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 @Mixin 注解进行方法注入 | Mixin 混合多个类优先级分析 )的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。