前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 MetaClass 进行方法注入构造方法 )

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

作者头像
韩曙亮
发布2023-03-30 10:42:09
2030
发布2023-03-30 10:42:09
举报
文章被收录于专栏:韩曙亮的移动开发专栏

文章目录

一、使用 MetaClass 注入构造方法


使用 MetaClass 注入构造方法 , 代码格式为 :

代码语言:javascript
复制
被注入构造方法的类.metaClass.constructor = { 闭包 }

为如下 Student 类 , 注入构造函数 , 传入 String 类型的参数 , 赋值给 name 成员 ;

代码语言:javascript
复制
class Student {
    def name;

    def hello() {
        println "Hello $name"
    }
}

注入构造函数代码如下 : 构造函数的函数名必须是 constructor ;

代码语言:javascript
复制
// 注入构造函数
// 方法名必须是 constructor
Student.metaClass.constructor = {
    String str ->
        new Student(name: str)
}

注意 , 构造函数的返回值必须是 Student 对象 ; 这里在注入的构造函数闭包中 , 可以设置若干构造函数参数 , 上述代码中 , 就为构造函数设置了 String 类型参数 ;

使用上述注入的构造函数 , 实例化 Student 对象 , 调用 hello 方法 , 可以成功打印出构造函数中传入的 “Tom” 参数 ;

代码语言:javascript
复制
// 使用注入的构造方法初始化 Student 类
def student = new Student("Tom")
student.hello()

二、完整代码示例


完整代码示例 :

代码语言:javascript
复制
class Student {
    def name;

    def hello() {
        println "Hello $name"
    }
}


// 注入构造函数
// 方法名必须是 constructor
Student.metaClass.constructor = {
    String str ->
        new Student(name: str)
}

// 使用注入的构造方法初始化 Student 类
def student = new Student("Tom")
student.hello()

执行结果 :

代码语言:javascript
复制
Hello Tom
在这里插入图片描述
在这里插入图片描述
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-01-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 一、使用 MetaClass 注入构造方法
  • 二、完整代码示例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档