Undefined Title

interoperability between Java and Groovy

2013-01-27

If you want to invoke a groovy script from Java, you can use ScriptEngine. It’s easy to give an initial value as a local variable to groovy script. And also even if the script takes a few command line arguments, that engine can give those values with using value name args which is an array of String.

import javax.script.*;

public class GroovyScripting {
  public static void main(String[] args) throws Exception {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("groovy");
    Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    
    bindings.put("counter", 0);
    bindings.put("args", new String[] {"hello", "world"});
    
    String LF = "\n";
    String code = ""
        + "counter += 1" + LF
        + "println args[0]" + LF
        + "['a':123, 3:'b']";
                    
    System.out.println(((java.util.Map)engine.eval(code)).get("a"));
    System.out.println(bindings.get("counter"));
  }
}

counter and args are local variables.

The output is like

hello
123
1

engine.eval(code) returns the value which is evaluated at the last of script. After the evaluation, you can see local variables thru Bindings. In this example, the last value is a Map.

Add a next dependency if you use maven.

<dependency>
  <groupId>org.codehaus.groovy</groupId>
  <artifactId>groovy-jsr223</artifactId>
  <version>2.0.0</version>
</dependency>