前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Groovy】MOP 元对象协议与元编程 ( 使用 Groovy 元编程进行函数拦截 | 实现 GroovyInterceptable 接口 | 重写 invokeMethod 方法 )

【Groovy】MOP 元对象协议与元编程 ( 使用 Groovy 元编程进行函数拦截 | 实现 GroovyInterceptable 接口 | 重写 invokeMethod 方法 )

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

文章目录

一、GroovyInterceptable 接口简介


定义 Groovy 类时 , 令该类实现 GroovyInterceptable 接口 , 该 GroovyInterceptable 接口继承自 GroovyObject 接口 ,

代码语言:javascript
复制
public interface GroovyInterceptable extends GroovyObject {
}

由上面的代码可知 , 在 GroovyInterceptable 接口中 , 没有在 GroovyObject 接口 的基础上 , 定义新的抽象方法 ;

二、重写 GroovyObject#invokeMethod 方法


定义 Student 实现 GroovyInterceptable 接口 ,

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

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

那么调用 Student 对象的任何方法 , 都会调用到 GroovyObject 的 invokeMethod 方法 ;

代码语言:javascript
复制
public interface GroovyObject {
    /**
     * Invokes the given method.
     *
     * @param name the name of the method to call
     * @param args the arguments to use for the method call
     * @return the result of invoking the method
     */
    Object invokeMethod(String name, Object args);
}

重写 Student 类中的 invokeMethod 方法 ,

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

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

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

三、GroovyInterceptable 接口拦截效果


GroovyInterceptable 接口 :

  • 没有实现 GroovyInterceptable 接口 :
    • 直接调用方法 : 不会触发 invokeMethod 方法 ;
    • 通过 invokeMethod 调用方法 : 会触发 invokeMethod 方法 ;
    • 调用不存在的方法 : 会报错 ;
  • 实现了 GroovyInterceptable 接口 :
    • 直接调用方法 : 会触发 invokeMethod 方法 ;
    • 通过 invokeMethod 调用方法 : 会触发 invokeMethod 方法 ;
    • 调用不存在的方法 : 不会报错 ;

四、完整代码示例


完整代码示例 :

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

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

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

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

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

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

执行结果 :

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 一、GroovyInterceptable 接口简介
  • 二、重写 GroovyObject#invokeMethod 方法
  • 三、GroovyInterceptable 接口拦截效果
  • 四、完整代码示例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档