您当前的位置: 首页 > 

韩曙亮

暂无认证

  • 3浏览

    0关注

    1068博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

韩曙亮 发布时间:2022-01-18 23:13:39 ,浏览量:3

文章目录
  • 一、通过 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
关注
打赏
1663594092
查看更多评论
立即登录/注册

微信扫码登录

0.1858s