Groovy 中的动态方法调用

Dynamic method invocation in Groovy

我想根据参数代码在方法上调用方法1方法2是吗是否为空

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

但是没有任何反应?我哪里错了? 如果我写

method(index)."method1"(code)

有效,但不能使三元运算符有效。

你可以这样做:

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

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

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