Find square of number using javascript (js) squareFunction - in Nashorn Javascript (js) Engine in Java 8




Program/ Example of Nashorn Javascript (js) Engine in Java 8 >
Find square of number using javascript (js) squareFunction

package nashorn1;
import java.io.FileReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Nashorn_calculateSquareOfNumberInJavascriptFunction {
   public static void main(String[] args) throws Exception {
         
          System.out.println("In java - START");
      
          // Get nashorn javascript engine
          ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
          // Pass the location of js file
          //engine.eval(new FileReader("E:/pocJmse/myNashornJavaScript.js"));
          //OR
            engine.eval("load('E:/pocJmse/myNashornJavaScript.js')");
          // NashornScriptEngine implements Invocable interface
          Invocable invocable = (Invocable) engine;
          // Call/Invoke js (javascript) function - Find square of number using js squareFunction
          System.out.println("In java - Call js (javascript) squareFunction to - Find square of number");

          Object squareResult = invocable.invokeFunction("squareFunction", 2);
          System.out.println("In java - squareResult = " + squareResult);
          System.out.println("In java - squareResult type = " + squareResult.getClass());
            System.out.println("In java - FINISH");
   }
}
/* OUTPUT
In java - START
In myNashornJavaScript.js
End myNashornJavaScript.js
In java - Call js (javascript) squareFunction to - Find square of number
In js function - Object type = [object Number]
In js function - Calulating square of 2
In java - squareResult = 4.0
In java - squareResult type = class java.lang.Double
In java - FINISH
*/


E:/pocJmse/myNashornJavaScript.js looks like this >
print('In myNashornJavaScript.js');
var squareFunction = function(num) {
   print("In js function - Object type = " + Object.prototype.toString.call(num));
   print('In js function - Calulating square of ' + num);
   return (num * num);
};

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 :