如何使用GroovyShell列出所有绑定变量

时间:2011-09-14 19:36:51

标签: binding groovy groovyshell

我是Groovy的新手。如何列出我传递给Binding构造函数的所有变量?

考虑到我有以下内容:

@Test
public void test() {

    List<String> outputNames = Arrays.asList("returnValue", "ce");

    String script = getScript();
    Script compiledScript = compileScript(script);
    CustomError ce = new CustomError("shit", Arrays.asList(new Long(1)));

    Map<String, Object> inputObjects = new HashMap<String, Object>();
    inputObjects.put("input", "Hovada");
    inputObjects.put("error", ce);

    Binding binding = new Binding(inputObjects);
    compiledScript.setBinding(binding);
    compiledScript.run();

    for (String outputName : outputNames) {
        System.out.format("outputName : %s  =  %s", outputName, binding.getVariable(outputName));
    }
}

private Script compileScript(String script) {
    GroovyShell groovyShell = new GroovyShell();
    Script compiledScript = groovyShell.parse(script);
    return compiledScript;
}

如何在groovy.script中迭代所有变量(通过hashMap)?

1 个答案:

答案 0 :(得分:13)

Script compiledScript表示脚本,如果你查看它的源代码,你会看到它有属性绑定和getter + setter,而Binding有一个变量“variables”。所以你去:

binding.variables.each{ 
  println it.key
  println it.value 
}

Map<String, String> ...

您还可以设置如下属性:

Binding binding = new Binding(inputObjects);
compiledScript.setBinding(binding);
compiledScript.setProperty("prop", "value");
compiledScript.run();

并将其存储到Binding变量中。