Friday, July 15, 2005

Janino in 30 seconds, using Jython

Janino looks powerful. It compiles expressions, scripts, classes, etc. either from source code or programmatically. But the code samples elicited my moan reflex.
  • The "Use Janino as an Expression Evaluator" code snippets look simple enough, but to really try them yourself, you need to: wrap in boilerplate, compile, tweak, execute, scratch head, add System.out.println() statements, remix ... keep that cycle up and you'll know what's going on after a while.
  • Or, just run the example classes with their command-line syntax. Simple enough... but we're trying to learn an API here, right? Command-line switches insulate us from the API, which is the opposite of what we want.
Enter Jython. The same code from the Expression Evaluator code snippets, remixed here in shot-glass form:
D:\>jython
Jython 2.1 on java1.4.2_06 (JIT: null)
Type "copyright", "credits" or "license" for more information.
>>> from org.codehaus.janino import ExpressionEvaluator
>>> from java.lang import Integer
>>> ee = ExpressionEvaluator("c > d ? c : d", Integer.TYPE, ["c","d"], [Integer.TYPE,Integer.TYPE] )
>>> ee.evaluate( [10,11] )
11
>>>
Nice. I typed as many Janino lines as boilerplate lines. Four lines in, I'm already seeing useful results. That actually makes me want to, I don't know, evaluate another expression:
>>> ee.evaluate( [5,2] )
5
>>>
It's going to be great fun exploring this API. ScriptEvaluator, ClassBodyEvaluator, Compiler, AST ... Jython users, start your engines.