【Groovy】MOP 元对象协议与元编程 ( 使用 Groovy 元编程进行函数拦截 | 通过 MetaClass#invokeMethod 方法调用类其它方法 )
2023-09-14 09:07:29 时间
一、通过 MetaClass#invokeMethod 方法调用类其它方法
注意在 invokeMethod 方法中 , 不能调用 invokeMethod 方法 , 这样调用肯定会出现无限循环递归 , 导致栈溢出 ;
此处只能通过调用 MetaClass#invokeMethod 方法 , 调用相关函数 ;
通过元类对象的 invokeMethod 方法 , 不会导致栈溢出 ;
获取该 Groovy 类的 metaClass , 然后调用 metaClass 的 invokeMethod 方法 , 传入调用对象 , 调用方法 , 方法参数 , 即可调用相关方法 ;
// 检查该类中是否定义 name 方法 , 参数是 args
def hasMethod = metaClass.invokeMethod(this, "respondsTo", name, args)
传入了的方法名 , 如果存在 , 则直接通过 metaClass.invokeMethod 调用该方法 ;
// 如果定义了该方法 , 则执行该方法
if (hasMethod) {
metaClass.invokeMethod(this, name, args)
}
二、完整代码示例
完整代码示例 :
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)
执行结果 :
invokeMethod : hello
Hello Tom
invokeMethod : hello1
相关文章
- 2 —— js语法 —— 对象和方法的声明 。变量提升。闭包
- js中判断对象是否为空的三种实现方法
- RF中采用python方法获取当月1号、上月1号、下月1号、当前日期N天后日期、当前日期N天前日期、指定月份总天数、上个月份、下个月份、当月最后1天日期、上个月最后1天日期、下个月最后1天日期
- Effective Java -- 对于所有对象都通用的方法
- JavaScript中判断对象类型的种种方法
- Array对象的方法实现(2)----Array.prototype.every和Array.prototype.fill(实现常规参数的功能)
- Array对象的方法实现(4)----Array.prototype.findIndex和Array.prototype.forEach(实现常规参数的功能)
- 各种语言执行入口的传参方法
- 在 JavaScript 中访问对象属性的 3 种方法
- Python编程学习:random.shuffle的简介、使用方法之详细攻略
- 【Groovy】MOP 元对象协议与元编程 ( Groovy 类内部和外部分别获取 metaClass | 分析获取 metaClass 操作的字节码 | HandleMetaClass 注入方法 )
- 【Groovy】MOP 元对象协议与元编程 ( Expando 动态类 | 创建动态类 | 为动态类增加字段和方法 )
- 【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 Mixin 混合进行方法注入 )
- 【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 ExpandoMetaClass 进行方法注入 )
- 【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 分析使用 MetaClass 进行方法注入前后 mateClass 类型变化 )
- 【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 MetaClass 注入静态方法 )
- 【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 Category 分类注入方法 )
- 【Groovy】MOP 元对象协议与元编程 ( 使用 Groovy 元编程进行函数拦截 | 实现 GroovyInterceptable 接口 | 重写 invokeMethod 方法 )
- 【Groovy】MOP 元对象协议与元编程 ( 通过 MetaMethod#invoke 执行 Groovy 方法 )
- strlen库函数求字符串的长度和三种模拟实现方法