Scripting in Java

It can sometimes be useful to externalize some business logic from Java to a scripting environment which allows you to modify the logic at runtime. You can store the script in an external file or in database, and load it on each run. With little effort you can even add a code editor (e.g. using the excellent Editarea) to your application.

Meet javax.script.

A well-known implementation of javax.script. ScriptEngine is Mozilla Rhino.

Java 6 SE comes with Rhino 1.6r2 bundled, so you don’t even need to add any jar to your project.

The nice thing about Rhino is that you can access the full Java API from the JavaScript it executes, and you can inject objects from Java to JavaScript, and the operations you perform on those objects from inside the scripting, are directly reflected into the Java instances of the Object.

Let’s take a look at an example:

Java code

final Session session = HibernateUtil.getSession(); 

final Code code = (Code) session.get(Code.class, "1"); 

final ScriptEngineManager manager = new ScriptEngineManager(); 
final ScriptEngine jsEngine = manager.getEngineByName(code.getType());

final Employee employee = new Employee();

jsEngine.put("employee", employee); 

Integer result = (Integer) jsEngine.eval(code.getCode()); 


JavaScript code (from code.getCode())


function main() { 
    employee.setName("JavaScript is my Name"); 
    employee.setName(employee.getName()+" !!!"); 
    return 1+2+3+4+5; 

This illustrates on how to load some JavaScript from a database, and have it executed by the ScriptEngine. The JavaScript can directly call the setter methods on the injected Employee object. The return code from the function main() is stored in the result variable.

By the way, you are not bound to use JavaScript. There are several JSR-223 script implementations, e.g. Groovy, Python, Ruby, Scheme, PHP, …

I think this can be really useful and I will certainly use it in some of my projects in the near future.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s