Program/ Example of Nashorn Javascript (js) Engine in Java 8 - call java methods from javascript (js) file - call java method from javascript to calculate square of number >
package nashorn10_CallJavaMethodsFromJs;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
/**
* How to call java methods from javascript (js) file
*
*/
public class CallJavaMethodsFromJs {
public static void main(String[] args) throws Exception {
System.out.println("In java - START");
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval("load('E:/pocJmse/myNashornJavaScript.js')");
System.out.println("In java - FINISH");
}
// This method will be called from Javascript (js)
// This method return square of value passed from js
public static int javaSquareMethod(int jsParameter) {
System.out.println("2 - In java - jsParameter = " + jsParameter);
return (jsParameter * jsParameter); // return square of value passed from js
}
}
/*OUTPUT
In java - START
In myNashornJavaScript.js
1 - In javascript (js) - call javaSquareMethod
2 - In java - jsParameter = 4
3 - In javascript (js) - javaSquareResult = 16
End myNashornJavaScript.js
In java - FINISH
*/
|
E:/pocJmse/myNashornJavaScript.js looks like this >
print('In myNashornJavaScript.js');
var CallJavaMethodsFromJs = Java.type('nashorn10_CallJavaMethodsFromJs.CallJavaMethodsFromJs');
//call java method to calculate square of number
print("1 - In javascript (js) - call javaSquareMethod");
var javaSquareResult = CallJavaMethodsFromJs.javaSquareMethod(4);
print('3 - In javascript (js) - javaSquareResult = ' + javaSquareResult);
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.