picture home | pixelblog | qt_tools

omino code blog

We need code. Lots of code.
David Van Brink // Mon 2006.12.11 13:14 // {java scripting}

Java 6, JavaScript

Java 6 is now available. There’s just one feature that caught my eye: JSR 223, support for JVM-based scripting languages.

Now, of course, that’s all wonderful, and they’ve got this full infrastructure to plug in any number of scriptable languages via a ScriptEngineFactory and that there’s all sorts of compliant languages that might be available… I’m sure it’s all quite fascinating.

The only thing I care about, though, is that, hooray, they include exactly one scripting language as standard in the JRE: EcmaScript, implemented by Rhino.

Now, of course, that’s all wonderful, and gives you the opportunity to add scripting to your application, oh how very moderne, obedy dobedy do and so fothe. But check out this super simple exciting usage! Forget all the power and generality, here’s a simple trick that solves a real problem that I bet you’ve had occasionally: simple text-based expression evaluation. Yeeha!

public static void main(String[] args) {
  RhinoScriptEngine e = new RhinoScriptEngine();
  try
  {
    Object o = e.eval("a = 24; b = 11; Math.sin(a) + b;");
    Console.print("result: " + o + " (" + o.getClass().getName() + ")");
  } catch (ScriptException e1)
  {
      // (probably a syntax error in your expression)
      e1.printStackTrace();
  }
}

Produces the following output:

   result: 10.094421637993376 (java.lang.Double)

Joy!

1 comments
Douglas // Tue 2006.12.12 23:5711:57 pm

Hey, that’s cool!

oh, i dont know. what do you think?



(c) 2003-2011 omino.com / contact poly@omino.com