在groovy中,你如何動態調用一個類的靜態方法?在groovy中,你如何動態調用一個類的靜態方法?
void callMethod(Class c, String staticmethodname){
//what goes here to call the static method of class c?
}
在groovy中,你如何動態調用一個類的靜態方法?在groovy中,你如何動態調用一個類的靜態方法?
void callMethod(Class c, String staticmethodname){
//what goes here to call the static method of class c?
}
瞧
void callMethod(Class c, String staticmethodname){
c."$staticmethodname"()
}
class test {
static someMethod() {
println "me"
}
}
callMethod(test, "someMethod")
你肯定能做到這一點的Java的方式:
c.getMethod(staticmethodname).invoke(null);
你可以這樣說:
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')
似乎不在常規控制檯工作。 – mfloryan 2010-12-17 20:54:47
正確的版本是:c.getMethod(staticmethodname).invoke(null); – mfloryan 2010-12-17 20:56:24
正確。現在它在控制檯中工作 – Bozho 2010-12-17 20:58:12