Showing posts with label Script Engine. Show all posts
Showing posts with label Script Engine. Show all posts

Thursday, 4 June 2015

Evaluating a math expression given in string form

With JDK1.6, you can use the built-in Javascript engine.


The Java Scripting functionality is in the javax.script package. This is a relatively small, simple API. The starting point of the scripting API is the ScriptEngineManager class. A ScriptEngineManager object can discover script engines through the jar file service discovery mechanism. It can also instantiate ScriptEngine objects that interpret scripts written in a specific scripting language. The simplest way to use the scripting API is as follows:
  1. Create a ScriptEngineManager object.
  2. Get a ScriptEngine object from the manager.
  3. Evaluate script using the ScriptEngine's eval methods.

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

public class Test {
  public static void main(String[] args) throws Exception{
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");
    String foo = "40+2";
    System.out.println(engine.eval(foo));
    } 
}