Java ScriptEngine get return value from JavaScript

Description

Java ScriptEngine get return value from JavaScript

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

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

    Object result = null;//from   w w w . j ava2s  . c o  m

    // Assigns 3 to result
    result = engine.eval("1 + 2;");
    System.out.println(result);
    // Assigns 7 to result
    result = engine.eval("1 + 2; 3 + 4;");
    System.out.println(result);
    // Assigns 6 to result
    result = engine.eval("1 + 2; 3 + 4; var v = 5; v = 6;");
    System.out.println(result);
    // Assigns 7 to result
    result = engine.eval("1 + 2; 3 + 4; var v = 5;");
    System.out.println(result);
    // Assigns null to result
    result = engine.eval("print(1 + 2)");
    System.out.println(result);

  }
}



PreviousNext

Related