From Java 8 we have a new Engine for running JavaScript, this is Nashorn.
What Java SE platform classes are involved in engine discovery and scripting?
How to execute JavaScript through the Java classes themselves in this new interpreter?
From Java 8 we have a new Engine for running JavaScript, this is Nashorn.
What Java SE platform classes are involved in engine discovery and scripting?
How to execute JavaScript through the Java classes themselves in this new interpreter?
The API that should be used to access the Nashorn Engine is javax.script
The identifier for access to Engine, "nashorn"
- Remembering that the engine is available from Java SE 8, that is, in previous versions the code below will not work.
What classes of the Java SE platform are involved in discovering the engine and running scripts?
The first class involved is javax.script.ScriptEngineManager - This class is responsible for implementing the discovery and retrieval of instances of the second important class for our example - javax.script.ScriptEngine .
ScriptEngineManager
As the class name suggests, a class object is responsible for managing not only the nashorn engine, but also other available engines.
ScriptEngine
In a simplified way, we can say that this class models the Engine itself by providing methods for running Scrits, both from Nashorn and other engines. Among its main methods are ScriptEngine.eval(Reader reader)
and ScriptEngine.eval(String script)
. The first one accepts Reader
, to which it is possible to pass an external file script to be executed. The second, a String
with the expressions. In short, the ScriptEngine
object is the entry point for the Nashorn interpreter, we should get an instance of it using ScriptEngineManager
.
ScriptException
It is an exception thrown by the eval
method and it is important to capture it to handle problems with the script.
How to run JavaScript through the Java classes themselves in this new interpreter?
Example
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Hello {
public static void main(String... args) {
ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine engine = engineManager.getEngineByName("nashorn");
try {
engine.eval("function sum(a, b) { return a + b; }");
System.out.println(engine.eval("sum(1, 2);"));
} catch (ScriptException e) {
System.out.println("Error executing script: " + e.getMessage());
}
}
}