Kyle
Kyle

Reputation: 22055

In groovy, how do you dynamically call a static method of a class?

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

Answers (3)

tim_yates
tim_yates

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

Bozho
Bozho

Reputation: 597392

You can certainly do it the java-way:

c.getMethod(staticmethodname).invoke(null);

Upvotes: 3

mfloryan
mfloryan

Reputation: 7685

Voila

void callMethod(Class c, String staticmethodname){
     c."$staticmethodname"()
}

class test {
  static someMethod() {
    println "me"
  }
}

callMethod(test, "someMethod")

Upvotes: 8

Related Questions