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

Java examples for Scripting:Bindings

Description

Passing Return Values from JavaScript to Java for external 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");
     try {//from   w  w w  . j a va 2  s  .  c  o  m

      engine.eval("load('test.js')");
      Invocable inv = (Invocable) engine;
      String returnValue2 = (String) inv.invokeFunction("returnName",
          new String[] { "Nashorn" });
      System.out.println("The returned value:" + returnValue2);
    } catch (ScriptException | NoSuchMethodException ex) {
      Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

  }
}

Related Tutorials