简体   繁体   English

Groovy - 将列表扩展为闭包参数

[英]Groovy - expanding list into closure arguments

Is it possible to have a list and use it as an argument for a closure signature that instead several variables? 是否有可能有一个列表并将其用作闭包签名的参数,而不是几个变量? The reason is that I have to call a closure from java code, and the java code won't know what variables the groovy closure needs. 原因是我必须从java代码调用一个闭包,而java代码不知道groovy闭包需要什么变量。

This is better served with an example. 用一个例子可以更好地服务。

Say I have a 'closure repository', where each closure might have different signatures. 假设我有一个'闭包存储库',每个闭包可能有不同的签名。 EG: 例如:

closures = [
    closureA: { int a, String b ->
        a.times {
            System.err.println(b);
        }
    },
    closureB: { int a, int b, String c ->
        (a+b).times {
            System.err.println(c);
        }
    }
]

Then I've got a method that I'm exposing to my java code to call these closures: 然后我有一个方法,我正在暴露于我的java代码来调用这些闭包:

def tryClosureExpansion(String whichClosure, Object ... args) {
    def c = closures[whichClosure]
    c.call(args)     // DOESNT COMPILE !
}

And it Java I'd call this method like this: 而Java我会像这样调用这个方法:

// these calls will happen from Java, not from Groovy
tryClosureExpansion("closureA", 1, "Hello");
tryClosureExpansion("closureB", 1, 5, "Hello more");

See above on the line that doesn't compile. 请参见上面未编译的行。 I feel like groovy is 'groovy' enough to handle something like this. 我觉得groovy是'groovy'足以处理这样的事情。 Any alternative that might fly? 任何可能会飞的替代品?

Does: 请问:

c.call( *args )

Work? 工作? Not at a computer atm to test it 不是在计算机上测试它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM