How do I import Java package in script?

Here you can see how to import a Java class so that you can use the class, creates an instance of it in the scripting environment. We want to print out the current date on the console. For this we need to import the Date class that’s packaged under the java.util package.

In the script we can import the java.util package using the following script let Date = Java.type("java.util.Date").

package org.kodejava.script;

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.util.function.Predicate;

public class ImportPackageExample {
    public static void main(String[] args) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByExtension("js");
        Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
        bindings.put("polyglot.js.allowHostAccess", true);
        bindings.put("polyglot.js.allowHostClassLookup", (Predicate<String>) s -> true);

        try {
            engine.eval(getScript());
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }

    private static String getScript() {
        return """                               
                let Date = Java.type("java.util.Date");
                let today = new Date();
                print(`Today is ${today.toString()}`);
                print(`today is ${today.getClass().getName()}`);
                """;
    }
}

This program prints the following line:

Today is Sun Oct 10 15:15:13 CST 2021
today is java.util.Date

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

How do I modify Java object in script?

This example show how to modify Java object from scripting environment. Below we manipulate a collection of string data. To pass data into the scripting engine we use a key-value binding to the script engine.

package org.kodejava.script;

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.util.List;
import java.util.ArrayList;

public class ModifiedJavaObjectFromScript {
    public static void main(String[] args) {
        // Creating an array of five colors
        List<String> colors = new ArrayList<>();
        colors.add("White");
        colors.add("Black");
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");

        // Obtain a ScriptEngine instance.
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByExtension("js");
        Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
        bindings.put("polyglot.js.allowHostAccess", true);

        // Place the colors list into the engine using colorList key.
        // After passing the list into the engine our script will be
        // able to read it.
        engine.put("colorList", colors);

        try {
            engine.eval(getScript());

            // Redisplay the modified version of colors.
            for (String color : colors) {
                System.out.println("In Java: " + color);
            }
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }

    private static String getScript() {
        // Below is our script to read the values of Java List that
        // contains string of colors. We also add some other colors
        // to the list object in the script environment.
        return """
                let index;
                let colors = colorList.toArray();

                for (index in colors) {
                    print(`In script: ${colors[index]}`);
                }

                colorList.add("Yellow");
                colorList.add("Purple");
                colorList.add("Orange");
                """;
    }
}

The output of the code snippet above is:

In script: White
In script: Black
In script: Red
In script: Green
In script: Blue
In Java: White
In Java: Black
In Java: Red
In Java: Green
In Java: Blue
In Java: Yellow
In Java: Purple
In Java: Orange

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

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.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

How do I evaluate or execute a script file?

This example demonstrated how to evaluate script that stored on a file. As we know that the eval() method can also accept a Reader object we can then read the script file using FileReader and pass it as the parameter to the eval() method of the ScriptEngine for further evaluation.

package org.kodejava.script;

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.io.File;
import java.io.Reader;
import java.io.FileReader;
import java.io.FileNotFoundException;

public class EvalScriptFile {
    public static void main(String[] args) {
        // Obtaining ECMAScript / JavaScript ScriptEngine.
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("ECMAScript");

        try {
            // Create an instance of File object that point to our
            // scripting file. An create a FileReader to read the
            // file to be passed to the ScriptEngine.eval() method.
            //
            // The file need to be placed in the same folder with
            // our class so it enable to read it. We can define the
            // full path to the file also to make easier for the
            // Reader to find it.
            File script = new File("helloworld.js");
            Reader reader = new FileReader(script);

            engine.eval(reader);
        } catch (FileNotFoundException | ScriptException e) {
            e.printStackTrace();
        }
    }
}

Our helloworld.js file.

console.log('Hello World');

for (let i = 0; i <= 10; i++) {
    console.log(`i = ${i}`);
}

The output of the code snippet:

Hello World
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
i = 10

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

How do I get the supported scripting engine?

package org.kodejava.script;

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

public class GetSupportedScriptingEngine {
    public static void main(String[] args) {
        // Creating an instance of ScriptEngineManager an get the list
        // of available ScriptEngineFactory.
        ScriptEngineManager manager = new ScriptEngineManager();
        List<ScriptEngineFactory> factories = manager.getEngineFactories();

        for (ScriptEngineFactory factory : factories) {
            System.out.println(
                    "EngineName      = " + factory.getEngineName());
            System.out.println(
                    "EngineVersion   = " + factory.getEngineVersion());
            System.out.println(
                    "LanguageName    = " + factory.getLanguageName());
            System.out.println(
                    "LanguageVersion = " + factory.getLanguageVersion());
            System.out.println(
                    "Extensions      = " + factory.getExtensions());
            System.out.println();

            List<String> names = factory.getNames();
            for (String name : names) {
                System.out.println("Engine Alias = " + name);
            }
        }
    }
}

The code above produces the following information.

EngineName      = Graal.js
EngineVersion   = Development Build
LanguageName    = ECMAScript
LanguageVersion = ECMAScript 262 Edition 11
Extensions      = [js, mjs]

Engine Alias = js
Engine Alias = JS
Engine Alias = JavaScript
Engine Alias = javascript
Engine Alias = ECMAScript
Engine Alias = ecmascript
Engine Alias = Graal.js
Engine Alias = graal.js
Engine Alias = Graal-js
Engine Alias = graal-js
Engine Alias = Graal.JS
Engine Alias = Graal-JS
Engine Alias = GraalJS
Engine Alias = GraalJSPolyglot

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

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.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

How do I evaluate a simple script?

The code below will evaluate a simple JavaScript that produces a “Hello World” message. To evaluate the script, the ScriptEngine provides us with some overloaded eval() methods, for instance an eval() methods that accept the script in string or in Reader object.

package org.kodejava.script;

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

public class EvaluatingScript {
    public static void main(String[] args) {
        // Obtaining the GraalVM Javascript engine
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("graal.js");

        try {
            // Evaluating a simple script
            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.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

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