To deal with interoperability with programs written in scripting languages, the Java community process has defined JSR-223, Scripting for the JavaTM Platform, a Java specification request that makes it possible to execute scripts written in other languages (such as Groovy, JavaScript, Ruby, or Jython to name of few) from within a Java program. For instance, we can write a Java program embedding a basic JavaScript snippet as follows:
package com.demo; import javax.script.*; public class JSR223Sample { public static void main(String[] args) throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); // expose object as variable to script engine.put("n", 5); // evaluate a script string. engine.eval("for(i=1; i<= n; i++) println(i)"); } }
We will get the following output from the IDE:
run: 1 2 3 4 5 BUILD SUCCESSFUL (total time: 0 seconds)
Starting from Scala's upcoming Version 2.11, this very convenient functionality will let you interpret scripts written in Scala as well. The following is an example that we can just run directly in the REPL (taken from the scala-lang.org documentation):
scala> import javax.script.ScriptEngineManager importjavax.script.ScriptEngineManager scala> val engine = new ScriptEngineManager().getEngineByName("scala") engine: javax.script.ScriptEngine = scala.tools.nsc.interpreter.IMain@7debe95d scala> engine.put("n", 5) n: Object = 5 scala> engine.eval("1 to n.asInstanceOf[Int] foreachprintln") 1 2 3 4 5 res4: Object = null
The engine context can bind the n
variable to the integer value 5
, which can be invoked in the one-liner script which consists of a foreach
lambda expression. The script, in this case, is only a side effect and does not return any interesting value.