Friday, August 24, 2012

How to Override Groovy Instance and Static Methods

Here are some examples on how to inject behavior into Groovy object methods. In the sample class below, method1 is an instance method with no arguments. method2 is also an instance method, but with a single String argument. method3 is a static method, which requires a slightly different way of injection.

Output from running groovy Test.groovy:

class Test {
    void method1() {
        println 'In method1'
    }

    void method1(String foo) {
        println "In method1 with String param of $foo"
    }

    static method2(String foo) {
        println "In static method2 with String param of $foo"
    }

    public static void main(String[] args) {

        def test = new Test()

        test.method1()
        test.method1("asdf")
        Test.method2("asdf")

        MetaMethod method1NoParamMethod = test.metaClass.pickMethod("method1", null as Class[])
        test.metaClass.method1 = { 
            println "augmenting no param method1"
            method1NoParamMethod.invoke(delegate)
        }

        MetaMethod method1StringParamMethod = test.metaClass.pickMethod("method1", String)
        test.metaClass.method1 = { String fooParam ->
            println "augmenting String param method1"
            method1StringParamMethod.invoke(delegate, fooParam)
        }

        MetaMethod method2Method = Test.metaClass.getStaticMetaMethod("method2", String)
        Test.metaClass.static.method2 = { String fooParam ->
            println "augmenting static method2"
            method2Method.invoke(delegate, fooParam)
        }

        test.method1()
        test.method1("asdf")
        Test.method2("asdf")

    }
}
In method1
In method1 with String param of asdf
In static method2 with String param of asdf
augmenting no param method1
In method1
augmenting String param method1
In method1 with String param of asdf
augmenting static method2
In static method2 with String param of asdf

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home