How do I create a ScriptEngine for JavaScript?

This examples demonstrate how to create a JavaScript interpreter or the ScriptEngine for running JavaScript script. The classes related to scripting is packaged under the javax.script package.

Java is since version 6 allows us to script Java using a scripting language such as JavaScript. This allows us to let the user of our program to change or add behavior to the program through scripting language.

package org.kodejava.example.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. "js" is the standar extension for
        // JavaScript script file.
        //
        ScriptEngine engine = manager.getEngineByExtension("js");

        //
        // Do something with the script engine.
        //
    }
}

Wayan Saryada

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

Leave a Reply