Reputation: 22055
In groovy, how do you dynamically call a static method of a class?
void callMethod(Class c, String staticmethodname){
//what goes here to call the static method of class c?
}
Upvotes: 4
Views: 5555
Reputation: 171194
You can do it like this:
def callMethod(Class c, String staticmethodname, args = null ) {
args ? c."$staticmethodname"( args ) : c."$staticmethodname"()
}
println callMethod( String.class, 'valueOf', 1 )
println callMethod( Calendar.class, 'getInstance' )
Upvotes: 2
Reputation: 597392
You can certainly do it the java-way:
c.getMethod(staticmethodname).invoke(null);
Upvotes: 3
Reputation: 7685
Voila
void callMethod(Class c, String staticmethodname){
c."$staticmethodname"()
}
class test {
static someMethod() {
println "me"
}
}
callMethod(test, "someMethod")
Upvotes: 8