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

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

一、使用 MetaClass 注入构造方法


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

被注入构造方法的类.metaClass.constructor = { 闭包 }

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

class Student {
    def name;
    def hello() {
        println "Hello $name"
    }
}

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

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


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


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

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

二、完整代码示例


完整代码示例 :

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()

执行结果 :

Hello Tom

image.png


目录
相关文章
|
Go 开发者
如何使用 Golang 实现继承:详细指南
【8月更文挑战第31天】
1597 0
|
缓存 IDE Go
记一次go module的坑
事情是这样的,因为小马本次要写一个go项目。但是因为一些权限问题,一些依赖包在内网小马获取不到,于是只能求助大大。大大给的策略就是他先把所有的依赖包go mod,然后go mod vendor迁移到项目目录vendor下进行本地依赖载入即可,也就是使用 go build -mod=vendor来编译即可。一切似乎看起来还是那么完美。然后正要起飞,直接翻车,现场如下。【这里插播一条发现,就是使用golang IDE go build 和使用命令行go build 的区别在于前者不会生成.exe文件】
1433 0
记一次go module的坑
|
Java 应用服务中间件
如果 JAVA 程序中抛出了 java.lang.OutOfMemoryError:Java heap space ,请讲一下解决问题的思路。
如果 JAVA 程序中抛出了 java.lang.OutOfMemoryError:Java heap space ,请讲一下解决问题的思路。
5609 0
解决办法:ImportError: 'module' object has no attribute 'check_specifier'
解决办法:ImportError: 'module' object has no attribute 'check_specifier'
346 0
|
SQL Oracle 关系型数据库
|
2天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8083 2
|
12天前
|
域名解析 人工智能 Linux
|
20天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
10357 13
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置