Reputation: 29669
I have 2 scripts, where I am trying to test passing an argument, and it fails. I examined the documentation for GroovyScriptEngine but it doesn't seem to handle the case where I want to pass a arg rather than a property value pair (in a binding).
Here is the error I get:
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)
Here are my scripts:
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") );
}
}
And this one:
//hello.groovy
println "hello.groovy"
for (arg in this.args ) {
println "Argument:" + arg;
}
Upvotes: 3
Views: 15771
Reputation: 4859
Even simpler, the Binding class has a Constructor which takes a String[], and add it as 'args' so you can just do this:
public class Test {
public static void main(String[] args) {
new Hello(new Binding(args)).run();
}
}
Upvotes: 3
Reputation: 12334
Hello is looking for a string array in the binding called args
. This is automatically provided to you when you run the script via the command line, but if you are running it outside of that context, you must add it to the Binding
yourself:
This will pass the arguments sent to Test
through to Hello
as-is:
public class Test {
public static void main(String[] args) {
Binding b = new Binding()
b.setVariable("args", args)
Hello h = new Hello(b);
h.run()
}
}
If you want to send specific arguments, you must construct the array yourself:
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()
}
}
Upvotes: 3