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

时间:2012-05-08 21:02:59

标签: groovy closures dynamic-programming

是否有可能有一个列表并将其用作闭包签名的参数,而不是几个变量?原因是我必须从java代码调用一个闭包,并且java代码不知道groovy闭包需要什么变量。

通过一个例子可以更好地服务。

假设我有一个'封闭存储库',每个封闭可能有不同的签名。 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);
        }
    }
]

然后我有一个方法,我正在暴露给我的java代码来调用这些闭包:

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

Java我会这样称呼这个方法:

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

见上面没有编译的行。我觉得groovy是'groovy'足以处理这样的事情。任何可能会飞的替代方案?

1 个答案:

答案 0 :(得分:9)

的作用:

c.call( *args )

工作?不是在计算机上测试它

相关问题