Groovy 中的动态方法调用

Xel*_*ian 4 methods groovy dynamic

我想根据参数代码是否为空来调用方法1或方法2

void add(def code, def index) {
    method(index).((code != null) ? "method1"(code) : "method2"())
}
Run Code Online (Sandbox Code Playgroud)

但什么也没发生?我的错在哪里?如果我写

method(index)."method1"(code)
Run Code Online (Sandbox Code Playgroud)

有效但不能使三元运算符起作用。

tim*_*tes 5

你可以这样做:

void add(def code, def index) {
    method(index).with { m ->
        (code != null) ? m."method1"(code) : m."method2"()
    }
}
Run Code Online (Sandbox Code Playgroud)

或者(正如 @IgorArtamonov 在上面的评论中指出的):

void add(def code, def index) {
    (code != null) ? method(index)."method1"(code) : method(index)."method2"()
}
Run Code Online (Sandbox Code Playgroud)