Java Reference
In-Depth Information
Using the JavaImporter Object
In JavaScript, you can use the simple names of classes using a JavaImporter object
in a with statement. Please refer to Chapter 4 for more details in the with statement.
JavaImporter is a Nashorn function object that can be used as a function or a
constructor. It accepts a list of Java packages and classes. You can create a JavaImporter
object as shown:
// Import all classes from the java.lang package
var langPkg = new JavaImporter(Packages.java.lang);
// Import all classes from the java.lang and java.util packages and the
// JFrame class from the javax.swing package
var pkg2 = JavaImporter(java.lang, java.util, javax.swing.JFrame);
Notice the use of the new operator in the first statement. The second statement does
not use the new operator; it used JavaImporter as a function. Both statements do
the same thing.
The following snippet of code creates a JavaImporter object and uses it in a with
statement:
// Create a Java importer for java.lang and java.util packages
var javaLangAndUtilPkg = JavaImporter(java.lang, java.util);
// Use the imported types in the with clause
with (javaLangAndUtilPkg) {
var list = new ArrayList();
list.add("one");
list.add("two");
System.out.println("Hello");
System.out.println("List is " + list);
}
Hello
List is [one, two]
Creating and Using Java Objects
Use the new operator with a constructor to create a new Java object in scripts. The
following snippet of code creates a String object in Nashorn:
// Create a Java String object
var JavaString = Java.type("java.lang.String");
var greeting = new JavaString("Hello");
 
Search WWH ::




Custom Search