2011-09-14 7 views
9

Groovyの新機能です。 Bindingコンストラクタに渡したすべての変数をリストするにはどうすればよいですか?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; 
} 

がどのように私はgroovy.scriptに(HashMapの上で)すべての変数を反復処理することができますか?

答えて

12

Script compiledScriptはスクリプトを表しています。ソースコードを見ると、プロパティバインディングとgetter + setterがあり、Bindingに変数「変数」があることがわかります。だから、行く:Map<String, String>については

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

を...

あなたもこのようなプロパティを設定することができます

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

をし、それがバインド変数に格納されています。

関連する問題