Sunday, March 07, 2010

JavaScript-Engine in a Java program

Some days ago I was experimenting on an easy way to evaluate a calculation saved within a String variable of my program.
After some searches and a very useful hint I finally found the Java "ScriptEngineManager" introduced in Java 6 (JavaDoc). This engine is a very useful extension to the Java programming language as it allows to natively import the functionality of (in this case) JavaScript (documentation).

With this knowledge I wrote this simple test-program to show the possibilities of this technology:

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class ScriptTest {

  public static void main(String[] args) {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
  try {
  Number ret = (Number) jsEngine.eval("10 + 5 * (2 +3 *6)");

  Boolean ret1 = (Boolean) jsEngine.eval("100 >= (6*5)");

jsEngine.put("Hallo", "Servus");
String ret2 = (String) jsEngine.eval("Hallo");
} catch (ScriptException ex) {

No comments: