Recently I've I experimented with embedding JavaScript in Java with Rhino. Previously I had written a Python utility that parses text files in an AWK like fashion by allowing an expression to be passed in on the command line. In Python writing such a utility is easy because of it's dynamic nature - a user provided expression can be bits of Python which are then eval'd on the fly. But I was curious if I could make it faster by rewriting it in a faster language such as Java.
Like many compiled languages Java has no eval. Consequently the question becomes "What's the best way of evaluating user provided expressions in Java?". There are various answers to this question, but I decided to look into embedding languages in Java.
Although most people are quick to point out that, in spite of their names, Java and JavaScript are very different languages JavaScript via Rhino is the one scripting language included with Java 6. Because of this JavaScript seemed like a natural choice for what I wanted to do.
It's possible to work either through Java 6's generic interface to get at Rhino or through various org.mozilla.* packages to get at Rhino directly . I had some performance issues with the former due to a helper function being unconditionally compiled with each call (more on this in a future post) so I decided to work with Rhino directly.
The result in my JCols utility. If you try it I'd love to hear about it.
While writing JCols I found Rhino's embedding documentation to be quite helpful.
Incidentally one of the things I like about Rhino is it's interactive shell. In Fedora a helpful wapper shell script called rhino is provided. Simply run it and try out JavaScript expressions. If you get a null pointer exception then get the newer version that has my fix.