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





一、GroovyInterceptable 接口简介



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

public interface GroovyInterceptable extends GroovyObject {
}

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





二、重写 GroovyObject#invokeMethod 方法



定义 Student 实现 GroovyInterceptable 接口 ,

class Student implements GroovyInterceptable{
    def name;

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

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

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 方法 ,

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 方法 ;
    • 调用不存在的方法 : 不会报错 ;




四、完整代码示例



完整代码示例 :

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

执行结果 :

invokeMethod : hello
invokeMethod : hello1

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值