How to Run Javascript in Java 8’s Nashorn Engine Programmatically

Asked

Viewed 361 times

6

From Java 8 we have a new engine for Javascript execution, this is Nashorn.

Which Java SE platform classes are involved in engine discovery and script execution?

How to run Javascript through the Java classes themselves in this new interpreter?

1 answer

6


The API that should be used to access the Nashorn Engine is javax.script

The identifier for Engine access, "nashorn" - Remembering that the engine is available from Java SE 8, ie in previous versions with code below will not work.

Which Java SE platform classes are involved in engine discovery and execution of scripts?

The first class involved is javax.script.Scriptenginemanager - This class has the responsibility of implementing the discovery and obtaining instances of the second important class for our example - javax.script.Scriptengine.

Scriptenginemanager

As the class name suggests, an object of hers is in charge of managing not only the nashorn engine, but also other available Engines.

Scriptengine

Simply put, we can say that this class models the engine itself by providing methods for the execution of the Scritps, both of Nashorn and other Engines. Among its main methods are the ScriptEngine.eval(Reader reader) and ScriptEngine.eval(String script). The first accepts a Reader, to which it is possible to pass an external file ccript to be executed. The second, a String with the expressions. In short, the object of ScriptEngine is the entry point for the Nashorn interpreter, we should get an instance of it using a ScriptEngineManager.

Scriptexception

It is an exception launched by the method eval It is important to capture it to deal with 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());
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.