开发者

How to list all binding variables with GroovyShell

开发者 https://www.devze.com 2023-04-05 10:18 出处:网络
I\'m very new to Groovy. How can I list all variables I passed to Binding constructor ? Considering I have following :

I'm very new to Groovy. How can I list all variables I passed to Binding constructor ?

Considering I have following :

@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("ou开发者_Go百科tputName : %s  =  %s", outputName, binding.getVariable(outputName));
    }
}

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

How can I iterate over all the variables (over the hashMap) in groovy.script ?


Script compiledScript represents the script, if you look at its source code, you'll see that it has property binding and getter+setter and Binding has a variable "variables". So you go :

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

For Map<String, String> ...

you can also set properties like this :

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

and it is stored into the Binding variables.

0

精彩评论

暂无评论...
验证码 换一张
取 消