Call/Invoke js (javascript) function - Find sum of numbers using js squareFunction - in Nashorn Javascript (js) Engine in Java 8



Program/ Example of Nashorn Javascript (js) Engine in Java 8 - Call/Invoke js (javascript) function - Find sum of numbers using js squareFunction >


package nashorn1;
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Nashorn_sumOfNumbersInJavascriptFunction {
   public static void main(String[] args) throws Exception {
          System.out.println("In java - START");
      
          // Get nashorn engine
          ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
          // Pass the location of js file
          engine.eval(new FileReader("E:/pocJmse/myNashornJavaScript.js"));
          // NashornScriptEngine implements Invocable interface
          Invocable invocable = (Invocable) engine;
          // Call/Invoke js (javascript) function - Find sum of numbers using js squareFunction
          System.out.println("In java - Call js (javascript) sumFunction to - Find sum of numbers");
          Object sumResult = invocable.invokeFunction("sumFunction", 2, 3);
          System.out.println("In java - sumResult = " + sumResult);
          System.out.println("In java - sumResult type = " + sumResult.getClass());
       System.out.println("In java - FINISH");
   }
}
/* OUTPUT
In java - START
In myNashornJavaScript.js
End myNashornJavaScript.js
In java - Call js (javascript) sumFunction to - Find sum of numbers
In js function - Calulating sum of 2 and 3
In java - sumResult = 5
In java - sumResult type = class java.lang.Integer
In java - FINISH
*/


E:/pocJmse/myNashornJavaScript.js looks like this >
print('In myNashornJavaScript.js');
var sumFunction = function(num1, num2) {
   print('In js function - Calulating sum of ' + num1 + ' and ' + num2);
   return (num1 + num2);
};
print('End myNashornJavaScript.js');


Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.

eEdit
Must read for you :