2013-04-16 66 views
2

我有2個腳本,我試圖測試傳遞參數,並失敗。我檢查了GroovyScriptEngine的文檔,但似乎沒有處理我想要傳遞參數而不是屬性值對(在綁定中)的情況。如何將參數傳遞給Groovy 2.0腳本?

這裏是我的錯誤:

C:\AeroFS\Work\Groovy_Scripts>groovy scriptengineexample.groovy 
hello, world 
Caught: groovy.lang.MissingPropertyException: No such property: args 
     for class: hello 
groovy.lang.MissingPropertyException: No such property: args for 
     class: hello 
     at hello.run(hello.groovy:4) 
     at Test.main(scriptengineexample.groovy:14) 

這裏是我的腳本:

import groovy.lang.Binding; 
import groovy.util.GroovyScriptEngine; 
import groovy.util.ResourceException ; 
import groovy.util.ScriptException ; 
import java.io.IOException ; 

public class Test { 
    public static void main(String[] args) throws IOException, 
      ResourceException, ScriptException { 
    GroovyScriptEngine gse = new GroovyScriptEngine([ '.' ] as String[]) 
    Binding binding = new Binding(); 
    binding.setVariable("input", "world"); 
    gse.run("hello.groovy", binding); 
    System.out.println("Output: " + binding.getVariable("output")); 
    } 
} 

這一個:

//hello.groovy 
println "hello.groovy" 
for (arg in this.args) { 
    println "Argument:" + arg; 
} 
+0

不應該設置變量(args,[「input」,「world」])? –

回答

3

你好正在尋找在一個字符串數組綁定稱爲args。當您運行通過命令行的腳本,這是自動提供給你,但如果你是這方面的外運行,則必須將其添加到Binding自己:

這將通過發送到Test參數Hello原樣:

public class Test { 
    public static void main(String[] args) { 
     Binding b = new Binding() 
     b.setVariable("args", args) 
     Hello h = new Hello(b); 
     h.run() 
    } 
} 

如果你想發送特定的參數,你必須構建自己的數組:

public class Test { 
    public static void main(String[] args) { 
     Binding b = new Binding() 
     b.setVariable("args", ["arg1", "arg2", "etc."]) 
     Hello h = new Hello(b) 
     h.run() 
    } 
} 
2

更簡單,綁定類有一個構造函數,需要一個String [],並將其添加爲'args',因此您可以這樣做:

public class Test { 
    public static void main(String[] args) { 
     new Hello(new Binding(args)).run(); 
    } 
}