ScriptEngineBuilder for Java

28 Aug, 2009 · 2 min read · #java #javascript

Java 6 allows you to execute and communicate with scripts written in any scripting language, using the Scripting API. However, the code needed to create a ScriptEngine and evaluate a set of script files within it, is quite verbose and throws several checked exceptions.

I decided to create a simple fluent Builder which can be used to create a ScriptEngine and execute a set of script files inside it. It also allows you to add Java Objects into the engine before executing the script files.

ScriptEngineBuilder #

import java.io.InputStreamReader;
import java.net.URL;

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

public class ScriptEngineBuilder {
    private ScriptEngine engine;

    public ScriptEngineBuilder(String shortName) {
        this.engine = new ScriptEngineManager().getEngineByName(shortName);
    }

    public ScriptEngineBuilder add(String scriptResource) {
        try {
            URL scriptURL = getClass().getResource(scriptResource);
            InputStreamReader scriptReader = new InputStreamReader(scriptURL.openStream());
            engine.eval(scriptReader);

            return this;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public ScriptEngineBuilder put(String key, Object value) {
        engine.put(key, value);
        return this;
    }

    public ScriptEngine build() {
        return engine;
    }
}

Applications can create an instance of ScriptEngineBuilder by passing the shortName of the engine to the constructor. Then they can invoke add() method for the script files to be evaluated (as classpath resource name). They can finally invoke build() to get the ScriptEngine instance.

Sample Invocation #

ScriptEngine engine = new ScriptEngineBuilder("js")
		.add("/script1.js").put("myObj", obj)
		.add("/script2.js")
		.build();

If you liked what you read, consider subscribing to the RSS feed in your favourite feed reader.