Java Reference
In-Depth Information
Using the Packages Global Object
Nashorn defines
a
ll Java packages as properties of a global variable named
Packages
.
For example, the
java.lang
and
javax.swing
packages may be referred to as
Packages.
java.lang
and
Packages.javax.swing
, respectively. The following snippet of code uses
the
java.util.List
and
javax.swing.JFrame
in Nashorn:
// Create a List
var list1 = new Packages.java.util.ArrayList();
// Create a JFrame
var frame1 = new Packages.javax.swing.JFrame("Test");
Nashorn declares
java
,
javax
,
org
,
com
,
edu
, and
net
as global variables that are
aliases for
Packages.java
,
Packages.javax
,
Packages.org
,
Packages.com
,
Packages.edu
,
and
Packages.net
, respectively. Class names in examples in this topic start with the
prefix
com
, for example,
com.jdojo.script.Test
. To use this class name inside the
JavaScript code, you may use
Packages.com.jdojo.script.Test
or
com.jdojo.script.Test
.
However, if a class name does not start with one of these predefined prefixes, you must
use the
Packages
global variable to access it; for example, if your class name is
p1.Test
,
you need to access it using
Packages.p1.Test
inside JavaScript code. The following
snippet of code uses the
java
and
javax
aliases for
Packages.java
and
Packages.javax
:
// Create a List
var list = new java.util.ArrayList();
// Create a JFrame
var frame = new javax.swing.JFrame("Test");
Using the Java Global Object
Accessing packages as the properties of the
Packages
object was also supported in Rhino
JavaScript in Java 7. Using the
Packages
object is slower and error-prone. Nashorn defines
a new global object called
Java
that contains many useful functions to work with Java
packages and classes. If you are using Java 8 or later, you should prefer using the
Java
object. The
type()
function of the
Java
object imports a Java type into the script. You
need to pass the fully qualified name of the Java type to import. In Nashorn, the following
snippet of code imports the
java.util.ArrayList
class and creates its object:
// Import java.util.ArrayList type and call it ArrayList
var ArrayList = Java.type("java.util.ArrayList");
// Create an object of the ArrayList type
var list = new ArrayList();
Search WWH ::
Custom Search