Executing scripts using java

This post explain how to execute code written in scripting language like php or javascript etc in java.

The scripts are executed by calling eval on an instance of ScriptEngine interface.
An instance of ScriptEngine is used to represent scripting language specific engines. For example in case of JavaScript, Mozilla Rhino provided out of the box by java implements the ScriptEngine interface.

We get an instance of ScriptEngine by using an instance of ScriptEngineManager. An instance of ScriptEngineManager is used to lookup and return a instance of ScriptEngine. It also holds one or more instance of ScriptEngines created by it in a collection. We can get an instance of ScriptEngine using the method “getEngineByName” on ScriptEngineManager as shown below

Main Class


package package1;

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

public class Demo1 {
    public static void main(String[] args) throws ScriptException {
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
        scriptEngine.eval("print('Hello, World')");
    }
}

Output

Hello, World

Leave a Reply