Groovy is one of the most popular dynamic JVM languages. Executing Groovy code in Java is equally simple. We are using ScriptEngine. println str is the Groovy syntax for printing a String:
public class GroovyCode {
public static void main(String[] args) throws ScriptException {
final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
final ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("Groovy");
final Bindings bindings1 = scriptEngine.createBindings();
bindings1.put("str", "Let's pass from Java to Groovy");
scriptEngine.eval(" println str", bindings1);
}
}
Here's the result of executing the code:
Let's pass from Java to Groovy
To run the previous code, make sure that you have Groovy installed locally and that you have included Groovy jars in the class path.
Here's an example of how to run it from the command prompt:
java -cp ".:/usr/local/opt/groovy/libexec/lib/*" com.mastering.spring.taskscheduling.dynamic.GroovyCode