zl程序教程

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

当前栏目

【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 MetaClass 进行方法注入普通方法 )

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

文章目录

一、使用 MetaClass 进行方法注入


定义 Student 类 ,

class Student {
    def name;
}

为该 Student 类注入一个 hello 方法 , 先获取 Student 类的 metaClass 成员 , 然后为其注入 hello 方法 , 使用 << 符号 , 后面带上一个闭包 , 即可注入方法 , 在闭包中 , delegate 就是 Student 对象 ;

// 向 Student 类注入 hello 方法
Student.metaClass.hello << {
    println delegate
    println "Hello ${delegate.name}"
}

创建 Student 实例对象 , 调用为 Student 类注入的 hello 方法 ,

def student = new Student(name: "Tom")
student.hello()

即可打印出

Student@5dd6264
Hello Tom

内容 , 其中 Student@5dd6264 是 MetaClass 中的 delegate 代理对象 ;

此处注意 , 注入方法使用 << 运算符 , 替换 / 拦截方法 使用 = 运算符 ;

方法注入后 , 在 类 的 metaClass 中注入的方法 , 在任何 Student 对象中 , 都可以调用被注入的 hello 方法 ;

但是在 对象 的 metaClass 中注入的方法 , 只有该 Student 对象才能调用被注入的 hello 方法 , 其它对象不能调用该注入的方法 ;

二、完整代码示例


完整代码示例 :

class Student {
    def name;
}

// 向 Student 类注入 hello 方法
Student.metaClass.hello << {
    println delegate
    println "Hello ${delegate.name}"
}

/*
    注入方法使用 <<
    替换 / 拦截方法 使用 =
 */

def student = new Student(name: "Tom")
student.hello()

执行结果 :

Student@5dd6264
Hello Tom