How do I create an instance of ScriptEngine class for JavaScript?

This example demonstrates how to create a JavaScript interpreter or the ScriptEngine to run JavaScript in Java. The classes related to scripting is packaged under the javax.script.* package. In this example we show you how to create the JavaScript engine by using the engine extension.

package org.kodejava.script;

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

public class GettingJavaScriptEngine {
    public static void main(String[] args) {
        // Creating an instance of ScriptManager. With ScriptManager in hand we
        // can create an interpreter or ScriptEngine to run JavaScript.
        ScriptEngineManager manager = new ScriptEngineManager();

        // Calling manager.getEngineByExtension("js") returns a ScriptEngine
        // implementation for JavaScript engine.
        ScriptEngine engine = manager.getEngineByExtension("js");

        // Do something with the script engine.
        System.out.println("Engine = " + engine);
    }
}

The output of the code snippet:

Engine = com.oracle.truffle.js.scriptengine.GraalJSScriptEngine@56235b8e

Maven Dependencies

<dependencies>
    <dependency>
        <!--https://search.maven.org/remotecontent?filepath=org/graalvm/js/js/21.2.0/js-21.2.0.jar-->
        <groupId>org.graalvm.js</groupId>
        <artifactId>js</artifactId>
        <version>21.2.0</version>
    </dependency>
    <dependency>
        <!--https://search.maven.org/remotecontent?filepath=org/graalvm/js/js-scriptengine/21.2.0/js-scriptengine-21.2.0.jar-->
        <groupId>org.graalvm.js</groupId>
        <artifactId>js-scriptengine</artifactId>
        <version>21.2.0</version>
    </dependency>
</dependencies>

Maven Central Maven Central

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.