开发者

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

开发者 https://www.devze.com 2023-01-31 08:15 出处:网络
In groovy, how do you dynamically call a static method of a class? voi开发者_JAVA百科d callMethod(Class c, String staticmethodname){

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

精彩评论

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