How do I get a ScriptEngine by language name and version?

This example show you how you can obtain a script engine for a specific language name and specific language version. In the code below we try to obtain script engine instance for ECMAScript version ECMAScript 262 Edition 11.

package org.kodejava.script;

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.util.List;

public class ScriptEngineSearch {
    public static void main(String[] args) {
        String languageName = "ECMAScript";
        String languageVersion = "ECMAScript 262 Edition 11";

        // Creating a ScriptEngineManager and get the list of available
        // engine factories.
        ScriptEngineManager manager = new ScriptEngineManager();
        List<ScriptEngineFactory> factories = manager.getEngineFactories();

        // We obtain a ScriptEngine from the available factories where
        // the language name is "ECMAScript" and the version is
        // "ECMAScript 262 Edition 11". ECMAScript is the standard name
        // for JavaScript programming language.
        //
        // If we found the desired language we then get the ScriptEngine
        // by calling factory's getScriptEngine() method.
        ScriptEngine engine = null;
        for (ScriptEngineFactory factory : factories) {
            String language = factory.getLanguageName();
            String version = factory.getLanguageVersion();

            if (language.equals(languageName)
                    && version.equals(languageVersion)) {
                engine = factory.getScriptEngine();
                break;
            }
        }

        if (engine != null) {
            try {
                engine.eval("print('Hello There')");
            } 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.