Created
August 24, 2012 17:00
-
-
Save dtanner/3452900 to your computer and use it in GitHub Desktop.
Examples of overriding groovy instance and static methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment