zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

方法对象执行编程协议 通过 Groovy Invoke
2023-09-14 09:07:29 时间





一、通过 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