开发者

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?

voi开发者_JAVA百科d callMethod(Class c, String staticmethodname){
     //what goes here to call the static method of class c?
}


Voila

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

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

callMethod(test, "someMethod")


You can certainly do it the java-way:

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


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' )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜