Java Reference
In-Depth Information
The following is an example of creating a Runnable object in JavaScript using
an anonymous function as a lambda expression. The Runnable object is used in the
constructor of the Thread class.
var Thread = Java.type("java.lang.Thread");
// Create a Thread using a Runnable object. The Runnable object is
// created using an anonymous function as a lambda expressions.
var thread = new Thread(function () {
print("Hello Thread");
});
// Start the thread
thread.start();
The Java equivalent of the JavaScript code using a lambda expression is as follows:
// Create a Thread using a Runnable object. The Runnable object is
// created using a lambda expression.
Thread thread = new Thread(() -> {
System.out.println("Hello Thread");
});
// Start the thread
thread.start();
Summary
You will need to import Java types into scripts before you can use create objects of that
Java in scripts. There are four ways to import a type in a script: using the Packages global
object, using the Java.type() method, using the importPackage() and importClass()
functions, and using JavaImporter in a with clause. 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. Therefore,
you can use the fully qualified names of any types in these packages to refer to the type.
You need to use the new operator along with the Java type to create Java objects in
scripts. Using the Java.type() method lets you import the Java types including array type
in uniform way. You can create an array object the same way you can create an object of
any other type.
Most of the time, calling overloaded Java methods are resolved by Nashorn. If you
want to call a specific version of an overloaded method from script, you can use the
bracket notation to specify the specific method signature. For example, pt["print
(java.lang.Object)"](10.5) calls the print(java.lang.Object) method on the
object reference named pt passing 10.5 as the argument to the method.
Nashorn lets you extends interfaces, abstract classes, and concrete classes in scripts
using the Java.extend() method. It lets you invoke the superclass methods on an object
using the Java.super() method.
 
Search WWH ::




Custom Search