Passing Return Values from JavaScript to Java for internal Javascript - Java Scripting

Java examples for Scripting:Bindings

Description

Passing Return Values from JavaScript to Java for internal Javascript

Demo Code

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.script.Invocable;
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();
    ScriptEngine engine = manager.getEngineByName("nashorn");
    String myF = "function a(width, length, avgDepth){var volume = avgDepth * width * length; "
        + " return volume * 1.8; } ";
    try {//from  www . j av a2s .  c  o  m
      engine.eval(myF);
      double width = 6.0;
      double length = 2.0;
      double depth = 5.0;
      Invocable inv = (Invocable) engine;
      double returnValue = (double) inv.invokeFunction("a", new Double[] {
          width, length, depth });
      System.out.println(returnValue);

    } catch (ScriptException | NoSuchMethodException ex) {
      Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

  }
}

Related Tutorials