Java ScriptEngineManager add global scope binding variables

Description

Java ScriptEngineManager add global scope binding variables

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

public class Main {
  public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    if (engine == null) {
      System.out.println("JavaScript engine is not available. ");

      return;//from w w  w  .  j ava  2s. com
    }
    String script = ""; 
    Object result;
    try {
      // Use global scope bindings variables 
      manager.put("num1", 10.0); 
      manager.put("num2", 20.0); 
      script = "num1 + num2"; 
      result = engine.eval(script); 
      System.out.println(script + " = " + result); 
    } catch (ScriptException e) {
      e.printStackTrace();
    } 
    
  }
}



PreviousNext

Related