How do I create an instance of ScriptEngine class 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.

Leave a Reply

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