Share this page 

Use Java scripting engine (JDK 1.6)Tag(s): Varia


import java.util.List;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptException;

public class Scripting {
  public static void main(String[] args) {
    try {
      
      // dump available engines
      ScriptEngineManager mgr = new ScriptEngineManager();
      List<ScriptEngineFactory> engines = mgr.getEngineFactories();
      for (ScriptEngineFactory engine : engines ) {
        System.out.println(engine.getEngineName()); 
        for ( String n: engine.getNames()) {
          System.out.println("Short name : " + n);
        }
      }
      /*
      output :
      
      Mozilla Rhino
      Short name : js
      Short name : rhino
      Short name : JavaScript
      Short name : javascript
      Short name : ECMAScript
      Short name : ecmascript
      */
      
      // now execute a small script
      ScriptEngine engine = mgr.getEngineByName("JavaScript");
      String myJSCode = "function myFunction() {" 
                      + "   return (40 + 2);"
                      + "}"
                      +"myFunction();";
      System.out.println(engine.eval(myJSCode));
            /*
            output :

            42            
            */

    } 
    catch (ScriptException ex) {
      ex.printStackTrace();
    }
  }
}
How to use Rhino to reach beyond JavaScript into Java