前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Groovy】MOP 元对象协议与元编程 ( 使用 Groovy 元编程进行函数拦截 | 通过 MetaClass#invokeMethod 方法调用类其它方法 )

【Groovy】MOP 元对象协议与元编程 ( 使用 Groovy 元编程进行函数拦截 | 通过 MetaClass#invokeMethod 方法调用类其它方法 )

作者头像
韩曙亮
发布2023-03-30 10:38:32
4240
发布2023-03-30 10:38:32
举报

文章目录

一、通过 MetaClass#invokeMethod 方法调用类其它方法


注意在 invokeMethod 方法中 , 不能调用 invokeMethod 方法 , 这样调用肯定会出现无限循环递归 , 导致栈溢出 ;

此处只能通过调用 MetaClass#invokeMethod 方法 , 调用相关函数 ;

通过元类对象的 invokeMethod 方法 , 不会导致栈溢出 ;

获取该 Groovy 类的 metaClass , 然后调用 metaClass 的 invokeMethod 方法 , 传入调用对象 , 调用方法 , 方法参数 , 即可调用相关方法 ;

代码语言:javascript
复制
        // 检查该类中是否定义 name 方法 , 参数是 args
        def hasMethod = metaClass.invokeMethod(this, "respondsTo", name, args)

传入了的方法名 , 如果存在 , 则直接通过 metaClass.invokeMethod 调用该方法 ;

代码语言:javascript
复制
        // 如果定义了该方法 , 则执行该方法
        if (hasMethod) {
            metaClass.invokeMethod(this, name, args)
        }

二、完整代码示例


完整代码示例 :

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

    def hello() {
        System.out.println "Hello ${name}"
    }

    @Override
    Object invokeMethod(String name, Object args) {
        System.out.println "invokeMethod : $name"

        /*
            注意在 invokeMethod 方法中 , 不能调用 invokeMethod 方法
            肯定会出现递归调用 , 导致栈溢出
            只能通过调用 MetaClass#invokeMethod 方法 , 调用相关函数
         */

        // 检查该类中是否定义 name 方法 , 参数是 args
        def hasMethod = metaClass.invokeMethod(this, "respondsTo", name, args)

        /*
            注意这里区分 Student 中的 invokeMethod 方法 与
            MetaClass 中的 invokeMethod 方法
         */

        // 如果定义了该方法 , 则执行该方法
        if (hasMethod) {
            metaClass.invokeMethod(this, name, args)
        }
    }
}

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

// 直接调用 hello 方法
student.hello()

// 调用不存在的方法 , 也会触发 invokeMethod 方法
student.hello1()

// 通过 GroovyObject#invokeMethod 调用 hello 方法
// 第二个参数是函数参数 , 如果为 void 则传入 null
//student.invokeMethod("hello", null)

// 获取 元方法
//MetaMethod metaMethod = student.getMetaClass().getMetaMethod("hello", null)
// 执行元方法
//metaMethod.invoke(student, null)

执行结果 :

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

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

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

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

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