java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 com.javacoderanch.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();
        }
    }
}