10

私は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)を反復処理するにはどうすればよいですか?

4

1 に答える 1

15

Script compiledScriptスクリプトを表します。そのソースコードを見ると、プロパティバインディングとgetter + setterがあり、バインディングには変数「変数」があることがわかります。だからあなたは行き​​ます:

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変数に保存されます。

于 2011-09-14T20:12:02.707 に答える