How do I get ScriptEngine by engine name?

This example shows how to get an instance of ScriptEngine by the engine name. Below we are trying to obtain the GraalVM JavaScript engine.

package org.kodejava.script;

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

public class GettingScriptEngineByName {
    public static void main(String[] args) {
        ScriptEngineManager manager = new ScriptEngineManager();

        // Obtain an instance of ScriptEngine using the engine name. For
        // example, we get a GraalVM JavaScript engine.
        ScriptEngine engine = manager.getEngineByName("graal.js");

        try {
            engine.eval("print('Hello World');");
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <!--https://search.maven.org/remotecontent?filepath=org/graalvm/js/js/21.3.0/js-21.3.0.jar-->
        <groupId>org.graalvm.js</groupId>
        <artifactId>js</artifactId>
        <version>21.3.0</version>
    </dependency>
    <dependency>
        <!--https://search.maven.org/remotecontent?filepath=org/graalvm/js/js-scriptengine/21.3.0/js-scriptengine-21.3.0.jar-->
        <groupId>org.graalvm.js</groupId>
        <artifactId>js-scriptengine</artifactId>
        <version>21.3.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.