Program/ Example of Nashorn Javascript (js) Engine in Java 8 - Import java packages in javascript - And use java classes in javascript >
package nashornJs;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
/**
*
* Import java packages in javascript - And use java classes in javascript
*
*/
public class MyNashornClass {
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");
}
}
/* OUTPUT
In java - START
In myNashornJavaScript.js
1) Import java packages in javascript
2) Import java packages in javascript - java.lang, java.util
3) Now, Lets use java.lang package imported above
4) Create java.util.ArrayList
5) add elements in java.util.ArrayList
6) Display java.util.ArrayList
Display javaArrayList = [1, b, cat]
End myNashornJavaScript.js
In java - FINISH
*/
|
E:/pocJmse/myNashornJavaScript.js looks like this >
print('In myNashornJavaScript.js');
// Import java packages in javascript
print('1) Import java packages in javascript');
var javaImports = new JavaImporter(java.lang, java.util);
print('2) Import java packages in javascript - java.lang, java.util');
print('3) Now, Lets use java.lang package imported above');
with (javaImports) {
print('4) Create java.util.ArrayList');
var javaArrayList = new ArrayList(); //ArrayList is in java.util.ArrayList package
print('5) add elements in java.util.ArrayList');
javaArrayList.add('1');
javaArrayList.add('b');
javaArrayList.add("cat");
//Let's use java.lang package imported above
print('6) Display java.util.ArrayList');
System.out.println("Display javaArrayList = " + javaArrayList); //System is in java.lang.System package
}
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.