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

Leave a Reply

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