Using Global and Engine Scope Bindings of Engines Created by the Same ScriptEngineManager - Java Scripting

Java examples for Scripting:Script Engines

Description

Using Global and Engine Scope Bindings of Engines Created by the Same ScriptEngineManager

Demo Code

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();

    manager.put("n1", 100);
    manager.put("n2", 200);

    ScriptEngine engine1 = manager.getEngineByName("JavaScript");
    engine1.put("engineName", "Engine-1");

    ScriptEngine engine2 = manager.getEngineByName("JavaScript");
    engine2.put("engineName", "Engine-2");

    String script = "var sum = n1 + n2; "
      + "print(engineName + ' - Sum = ' + sum)";

    try {//  ww  w.  j  av  a  2s  . co  m
      engine1.eval(script);
      engine2.eval(script);

      engine1.put("n2", 1000);
      engine2.put("n2", 2000);

      engine1.eval(script);
      engine2.eval(script);
    }
    catch (ScriptException e) {
      e.printStackTrace();
    }
  }
}

Result


Related Tutorials