欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

【Groovy】MOP 元对象协议与元编程 ( 通过 MetaMethod#invoke 执行 Groovy 方法 )

发布时间:2025/6/17 编程问答 34 豆豆
生活随笔 收集整理的这篇文章主要介绍了 【Groovy】MOP 元对象协议与元编程 ( 通过 MetaMethod#invoke 执行 Groovy 方法 ) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

文章目录

  • 一、通过 MetaMethod#invoke 执行 Groovy 方法
  • 二、完整代码示例





一、通过 MetaMethod#invoke 执行 Groovy 方法



已经定义 Groovy 类 Student , 并创建该类对象 ;

class Student {def name;def hello() {println "Hello ${name}"} }def student = new Student(name: "Tom")

通过 MetaMethod#invoke 执行 Groovy 方法 :

首先 , 获取 Groovy 对象的 MetaClass ,

student.getMetaClass()

然后 , 调用 MetaClass#getMetaMethod 方法 获取 MetaMethod 对象 ,

MetaMethod metaMethod = student.getMetaClass().getMetaMethod("name", null)

最后 , 调用 MetaMethod#invoke 方法 , 执行获取的 MetaMethod 对应的 Groovy 方法 ;

metaMethod.invoke(student, null)



二、完整代码示例



完整代码示例 :

class Student {def name;def hello() {println "Hello ${name}"} }def student = new Student(name: "Tom")// 直接调用 hello 方法 student.hello()// 通过 GroovyObject#invokeMethod 调用 hello 方法 // 第二个参数是函数参数 , 如果为 void 则传入 null student.invokeMethod("hello", null)// 获取 元方法 MetaMethod metaMethod = student.getMetaClass().getMetaMethod("name", null) // 执行元方法 metaMethod.invoke(student, null)

执行结果 :

Hello Tom Hello Tom Hello Tom

总结

以上是生活随笔为你收集整理的【Groovy】MOP 元对象协议与元编程 ( 通过 MetaMethod#invoke 执行 Groovy 方法 )的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。