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

【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 MetaClass 注入静态方法 )

作者头像
韩曙亮
发布2023-03-30 10:41:53
1940
发布2023-03-30 10:41:53
举报

文章目录

一、使用 MetaClass 注入静态方法


使用 MetaClass 注入静态方法 , 可以使用如下代码实现 :

代码语言:javascript
复制
类名.metaClass.'static'.被注入的静态方法名 = { 闭包 }

定义 Student 类 , 其中定义 name 成员 ;

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

使用上述语法 , 向 Student 类注入 hello 静态方法 ;

代码语言:javascript
复制
// 向 Student 类注入 hello 静态方法
Student.metaClass.'static'.hello = {
    println "Hello Student ${delegate.name}"
}

注意这里在 被注入的 hello 静态方法中 , 使用了 delegate ,

  • 如果使用 Student 类调用 hello 方法 , 则 delegate 就是 Student 类 ;
代码语言:javascript
复制
// 通过 Student 类调用静态方法
Student.hello()
  • 如果使用 Student 对象调用 hello 方法 , 则 delegate 就是 Student 对象 ;
代码语言:javascript
复制
// 通过 Student 对象调用静态方法
def student = new Student(name: "Tom")
student.hello()

二、完整代码示例


完整代码示例 :

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

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

// 通过 Student 类调用静态方法
Student.hello()

// 通过 Student 对象调用静态方法
def student = new Student(name: "Tom")
student.hello()

执行结果 :

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

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

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

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

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