zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

方法注入对象编程协议 使用 分析 进行
2023-06-13 09:18:00 时间

文章目录

一、使用 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

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