您当前的位置: 首页 > 

韩曙亮

暂无认证

  • 0浏览

    0关注

    1068博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

韩曙亮 发布时间:2022-01-25 18:55:51 ,浏览量:0

文章目录
  • 一、使用 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 2 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
关注
打赏
1663594092
查看更多评论
立即登录/注册

微信扫码登录

0.0422s