Java ScriptEngine assign return value from JavaScript to Result Object

Description

Java ScriptEngine assign return value from JavaScript to Result Object

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

    Result result = new Result();
    engine.put("result", result);

    // Store the script in a String
    String script = "3 + 4; result.setValue(101);";

    engine.eval(script);//  w ww.j av  a 2  s  .c o m

    int returnedValue = result.getValue(); // Will be 101
    System.out.println("Returned value is " + returnedValue);
  }
}
public class Result {
  private int val = -1;

  public void setValue(int x) {
    val = x;/*from www .j  av  a  2 s.c o m*/
  }

  public int getValue() {
    return val;
  }
}



PreviousNext

Related