2011-09-14 46 views
9

我對Groovy非常陌生。如何列出傳遞給綁定構造函數的所有變量?如何使用GroovyShell列出所有綁定變量

考慮到我有以下幾點:

@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; 
} 

我如何可以遍歷所有的變量(在HashMap中)在groovy.script?

回答

12

Script compiledScript代表腳本,如果你看看它的源代碼,你會發現它具有屬性綁定和getter + setter,Binding有一個變量「變量」。所以你去:

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(); 

,並存儲到綁定變量。