我有两个脚本,我试图测试传递一个参数,但失败了。我检查了GroovyScriptEngine的文档,但它似乎不能处理我希望传递参数而不是属性值对(在绑定中)的情况。
下面是我得到的错误:
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;
}发布于 2013-04-18 03:23:57
Hello在名为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()
}
}发布于 2013-05-07 14:57:50
更简单的是,绑定类有一个构造函数,它接受一个String[],并将其添加为'args‘,这样您就可以这样做:
public class Test {
public static void main(String[] args) {
new Hello(new Binding(args)).run();
}
}https://stackoverflow.com/questions/16046993
复制相似问题