java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 com.javacoderanch.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.