Java Reference
In-Depth Information
scripting extension available is Nashorn, although other scripting environ‐
ments (such as Groovy or JRuby) can also be made available.
ScriptEngine
This class represents the script engine responsible for maintaining the environ‐
ment in which our scripts will be interpreted.
Bindings
This interface extends Map and provides a mapping between strings (the names
of variables or other symbols) and scripting objects. Nashorn uses this to
implement the ScriptObjectMirror mechanism for interoperability.
In practice, most applications will deal with the relatively opaque interface offered
by methods on ScriptEngine such as eval() , get() , and put() , but it's useful to
understand the basics of how this interface plugs in to the overall scripting API.
Advanced Nashorn
Nashorn is a sophisticated programming environment, which has been engineered
to be a robust platform for deploying applications, and to have great interoperability
with Java. Let's look at some more advanced use cases for JavaScript to Java integra‐
tion, and examine how this is achieved by looking inside Nashorn at some imple‐
mentation details.
Calling Java from Nashorn
As each JavaScript object is compiled into an instance of a Java class, it's perhaps not
surprising that Nashorn has seamless integration with Java—despite the major dif‐
ference in type systems and language features. However, there are still mechanisms
that need to be in place to get the most out of this integration.
We've already seen that we can directly access Java classes and methods from Nas‐
horn, for example:
$ jjs - Dkey = value
jjs > print ( java . lang . System . getProperty ( "key" ));
value
Let's take a closer look at the syntax and see how to achieve this support in Nashorn.
JavaClass and JavaPackage
From a Java perspective, the expression java.lang.System.getProperty("key")
reads as fully qualified access to the static method getProperty() on
java.lang.System . However, as JavaScript syntax, this reads like a chain of prop‐
erty accesses, starting from the symbol java —so let's investigate how this symbol
behaves in the jjs shell:
jjs > print ( java );
[ JavaPackage java ]
Search WWH ::




Custom Search