「Groovy」- Metaprogramming

问题描述

该笔记将记录:在 Apache Groovy 中,与元编程相关内容,以及常见问题的处理方法。

解决方案

Metaprogramming

为对象添加新属性及方法

class Foo {}

f = new Foo()

f.metaClass.unVariable = "something"
assert f.hasProperty("unVariable") == true
assert f.unVariable == "something"

f.metaClass.unMethod = { println "Hello World." }
assert f.unMethod() == "Hello World."

invokeMethod

在方法调用前,如果实现 invokeMethod() 方法,将调用该方法:

class MyClass implements GroovyInterceptable {

    def invokeMethod(String name, args) {
        System.out.println("This method is called method $name")
        def metaMethod = metaClass.getMetaMethod(name, args)
        metaMethod.invoke(this, args)
    }

    def myMethod() {
        "Hi!"
    }
}

def instance = new MyClass()
instance.myMethod()

或者,通过 metaClass 实现:

Integer.metaClass.invokeMethod = { String name, args ->
    println("This method is called method $name")
    def metaMethod = delegate.metaClass.getMetaMethod(name, args)
    metaMethod.invoke(delegate, args)
}

1.toString()

参考文献

How to verify if an object has certain property?
Dynamically add a property or method to an object in groovy
The Apache Groovy programming language – Runtime and compile-time metaprogramming
reflection – Find out a method’s name in Groovy – Stack Overflow