How do I evaluate a simple script?

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

package org.kodejava.example.script;

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

public class EvaluatingScript {
    public static void main(String[] args) {
        //
        // Obtaining JavaScript' ScriptEngine from the ScriptManager
        // using the engine extension.
        //
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine js = manager.getEngineByExtension("js");

        try {
            //
            // Evaluating a simple script
            //
            js.eval("print('Hello World')");
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
}

Wayan Saryada

Programmer, runner, recreational diver, live in the island of Bali, Indonesia 🇮🇩. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply