Chapter 9. JavaScript on Java with Nashorn
9.1 Develop Javascript code that creates and uses Java members such as Java objects, methods, JavaBeans, Arrays, Collections, Interfaces.
Nashorn is the only JavaScript engine included in the JDK. However, you can use any script engine compliant with JSR 223
To get an instance of the Nashorn engine, pass in “nashorn”. Alternatively, you can use any of the following: “Nashorn”, “javascript”, “JavaScript”, “js”, “JS”, “ecmascript”, “ECMAScript”.
Command line tools:
Nashorn interprets Java packages as JavaPackage objects, and Java classes as JavaClass function objects, which can be used as constructors for the classes.
The Java.type()
function takes a string with the fully qualified Java class name, and returns the corresponding JavaClass function object.
Accessing Class and Instance Members
Extending Java Classes/Interfaces
You can extend a class using the Java.extend() function that takes a Java type as the first argument and method implementations (in the form of JavaScript functions) as the other arguments. Below shows a script that extends the java.lang.Runnable interface and uses it to construct a new java.lang.Thread object.
Nashorn can automatically extend single abstract method (SAM) classes if you provide the function for implementing the method as the argument to the constructor.
Restricting Script Access to Specified Java Classes
The jdk.nashorn.api.scripting.ClassFilter
interface enables you to restrict access to specified Java classes from scripts run by a Nashorn script engine
Previous Chapter 8. Use Java SE 8 Date/Time API