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

简介: 【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 @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 混合多个类优先级分析


如果定义了 2 22 个注入方法类 , 其中都定义了 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


目录
相关文章
Linux:nohup、&、 2>&1、/dev/null
Linux:nohup、&、 2>&1、/dev/null
vscode中进行提问,字体怎么调整大小
vscode中进行提问,字体怎么调整大小
615 1
|
存储 Java
A timeout exceeded while waiting to proceed with the request, please reduce your request rate【已解决】
A timeout exceeded while waiting to proceed with the request, please reduce your request rate【已解决】
1282 0
|
分布式计算 运维 监控
Apache Doris Grafana监控指标介绍
整个集群重点关注的几个指标。
1300 0
Apache Doris Grafana监控指标介绍
|
存储 缓存 安全
Ehcache优缺点以及分布式详解
ehcahe的介绍 EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。Ehcache是一种广泛使用的开源Java分布式缓存。
14934 0