Java ScriptEngine pass parameters to script

Description

Java ScriptEngine pass parameters to script


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

public class Main {
  public static void main(String[] args) {
    // Get the Nashorn engine
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    // msg is a variable
    // that we have not declared in the script
    String script = "print(msg)";

    try {/*from   ww  w. j  a  va2 s. c  o m*/
      // Store a parameter named msg in the engine
      engine.put("msg", "Hello from the Java program");

      // Execute the script
      engine.eval(script);
    } catch (ScriptException e) {
      e.printStackTrace();
    }
  }
}



PreviousNext

Related