Collecting the Return Value of a Script in a Result Object - Java Scripting

Java examples for Scripting:Run Script

Description

Collecting the Return Value of a Script in a Result Object

Demo Code

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

    String script = "3 + 4; result.setValue(101);";

    engine.eval(script);//from   w ww.j  ava  2 s .  com

    int returnedValue = result.getValue(); // Will be 101
    System.out.println("Returned value is " + returnedValue);
  }
}

class Result {
  private int val = -1;

  public void setValue(int x) {
    val = x;
  }

  public int getValue() {
    return val;
  }
}

Related Tutorials