我是Groovy的新手。如何列出我传递给绑定构造函数的所有变量?
考虑到我有以下几点:
@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)?
发布于 2011-09-15 04:12:03
变量代表脚本,如果你看一下它的源代码,你会发现它有属性绑定,getter+setter和绑定有一个变量“Script compiledScript”。所以你会说:
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();并将其存储在绑定变量中。
https://stackoverflow.com/questions/7421993
复制相似问题