Java Reference
In-Depth Information
JavaScript does not import all classes from the
java.lang
package automatically
because JavaScript classes with the same names, for example,
String
,
Object
,
Numbe
r,
and so on, will conflict with class names in the
java.lang
package. To use a class from
the
java.lang
package, you can import it or use the
Packages
or
Java
global object to use
its fully qualified name. You cannot import all classes from the
java.lang
package. The
following snippet of code generates an error because the
String
class name is already
defined in JavaScript:
// Load the compatibility module. It is needed in Nashorn, not in Rhino.
load("nashorn:mozilla_compat.js");
// Will cause a conflict with String object in Nashorn
importClass(java.lang.String);
If you want to use the
java.lang.String
class, you need to use its fully qualified
name. The following snippet of code uses the built-in JavaScript
String
class and the
java.lang.String
class:
var javaStr = new java.lang.String("Hello"); // Java String class
var jsStr = new String("Hello"); // JavaScript String class
If a class name in the
java.lang
package does not conflict with a JavaScript top-
level class name, you can use the
importClass()
function to import the Java class. For
example, you can use the following snippet of code to use the
java.lang.System
class:
// Load the compatibility module. It is needed in Nashorn, not in Rhino.
load("nashorn:mozilla_compat.js");
importClass(java.lang.System);
var jsStr = new String("Hello");
System.out.println(jsStr);
In this snippet of code,
jsStr
is a JavaScript
String
that has been passed to the
System.out.println()
Java method that accepts a
java.lang.String
type. JavaScript
takes care of the conversion from a JavaScript type to a Java type automatically in
such cases.
Search WWH ::
Custom Search