Sunday, March 7, 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)");
  System.out.println(ret.doubleValue());

  Boolean ret1 = (Boolean) jsEngine.eval("100 >= (6*5)");
  System.out.println(ret1.booleanValue());

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

No comments:

Post a Comment

Golang setup PATH

Quite recently we startet in the company to use and write some Go programs. I love Go. It's easy to learn, read and modify. One of the m...