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')
はしていないようですGroovyコンソールで動く – mfloryan
正しいバージョンは以下のようになります:c.getMethod(staticmethodname).invoke(null); – mfloryan
が正しい。今それはコンソールで動作します – Bozho