Java Reference
In-Depth Information
jjs > print ( java . lang . System );
[ JavaClass java . lang . System ]
So java is a special Nashorn object that gives access to the Java system packages,
which are given the JavaScript type JavaPackage , and Java classes are represented by
the JavaScript type JavaClass . Any top-level package can be directly used as a pack‐
age navigation object, and subpackages can be assigned to a JavaScript object. This
allows syntax that gives concise access to Java classes:
jjs > var juc = java . util . concurrent ;
jjs > var chm = new juc . ConcurrentHashMap ;
In addition to navigation by package objects, there is another object, called Java ,
which has a number of useful methods on it. One of the most important is the
Java.type() method. This allows the user to query the Java type system, and get
access to Java classes. For example:
n
jjs > var clz = Java . type ( "java.lang.System" );
jjs > print ( clz );
[ JavaClass java . lang . System ]
If the class is not present on the classpath (e.g., specified using the -cp option to
jjs ), then a ClassNotFoundException is thrown ( jjs will wrap this in a Java Runti
meException ):
jjs > var klz = Java . type ( "Java.lang.Zystem" );
java . lang . RuntimeException : java . lang . ClassNotFoundException :
Java . lang . Zystem
The JavaScript JavaClass objects can be used like Java class objects in most cases
(they are a slightly different type—but just think of them as the Nashorn-level mir‐
ror of a class object). For example, we can use a JavaClass to create a new Java
object directly from Nashorn:
jjs > var clz = Java . type ( "java.lang.Object" );
jjs > var obj = new clz ;
jjs > print ( obj );
java . lang . Object @ 73 d4cc9e
jjs > print ( obj . hashCode ());
1943325854
// Note that this syntax does not work
jjs > var obj = clz . new ;
jjs > print ( obj );
undefined
However, you should be slightly careful. The jjs environment automatically prints
out the results of expressions—which can lead to some unexpected behavior:
jjs > var clz = Java . type ( "java.lang.System" );
jjs > clz . out . println ( "Baz!" );
Search WWH ::




Custom Search