Java Reference
In-Depth Information
You can also combine the two statements into one. Make sure to add the call to
Java.type() method in a pair of parentheses; otherwise, the statement will generate
an error thinking that Java.type is a constructor function and you are trying to create a
Nashorn object using a constructor function:
// Create an object of the java.util.ArrayList type
var list = new ( Java.type("java.util.ArrayList") ) ;
In the code, you call the imported type returned from the Java.type() function as
ArrayList that is also the name of the class that is imported. You do it to make the next
statement read as if it was written Java. Readers of the second statement will know that
you are creating an object of the ArrayList class. However, you can give the imported
type any name you want. The following snippet of code imports java.util.ArrayList
and calls it MyList :
// Import java.util.ArrayList type and call it MyList
var MyList = Java.type("java.util.ArrayList");
// Create an object of the MyList type
var list2 = new MyList();
Using the importPackage() and importClass() Functions
Rhino JavaScript allowed using the simple names of the Java types in script. Rhino
JavaScript had two built-in functions called importPackage() and importClass()
to import all classes from a package and a class from a package, respectively. For
compatibility reasons, Nashorn keeps these functions. To use these functions in Nashorn,
you need to load the compatibility module from mozilla_compat.js file using the load()
function. The following snippet of code rewrites the above logic in the previous section
these functions:
// Load the compatibility module. It is needed in Nashorn, not in Rhino.
load("nashorn:mozilla_compat.js");
// Import ArrayList class from the java.util package
importClass(java.util.ArrayList);
// Import all classes from the javax.swing package
importPackage(javax.swing);
// Use simple names of classes
var list = new ArrayList();
var frame = new JFrame("Test");
 
Search WWH ::




Custom Search