Embedded Javascript

Posted: April 22, 2010 in Uncategorized
Tags:

A recent project I’ve been working on has me looking at embedding a scripting language inside of the JVM. We have the need for a large number of scripts that will control the overall flow of an application written in Java. A number of popular scripting languages can now be embedded in the JVM. We choose Javascript with the Rhino engine but we could have also used Python with Jython.

Rhino

Rhino is a Mozilla foundation project that provides a Javascript interpreter that runs inside of the JVM. Your Java programs can easily pass a string of Javascript code to the interpreter and tell it to run. Your Javascript programs can also instantiate classes written in Java or make calls to Java objects created by the rest of your program.

Invoking Javascript
The Java code snippet

Context context = ContextFactory.enter();
Scriptable scope = context.initStandardObjects();
scope.evaluateString('for(var i=0;i<10;i++) { ' +
                             'java.lang.System.out.println(i);' +
                          '}');

Will execute the Javascript code passed to evaluateString (a for loop in this case). Notice how easy it is to call Java objects from your embedded Javascript code. You aren’t restricted to the standard Java classes you can also call into (or instantiate) any Java classes you write.

Type Safety

Java is a fairly strongly typed language, Javascript is not. What does embedding Javascript in your Java code mean for type safety? Your Java code will continue to check the types of objects at compile time but any Javascript code continues to be un-typed. Let’s say you have a method that returns a map to objects (say Map<String,Object> ). Maybe you know that the object pointed to by the key “name” always is a String; with Javascript you can just treat the object as a String. For example you could write a line of Javascript like myMap.get("name").substr(2);. With Java you would have to use casting or come up with a better data-structure than a map of objects. If you like type-safety you probably think it is good that Java forces you to fix your data-structure design but if your not a fan of all the work, code, and extra classes that is often entailed in doing so then you might appreciate how ignoring types lets you get by with far fewer lines of Javascript than the equivalent Java.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s