Java Reference
In-Depth Information
Note that one of the problems with interacting with a scripting engine directly from
Java is that we don't normally have any information about what the types of values
are.
Nashorn has a fairly close binding to much of the Java type system, so we need to be
somewhat careful, however. When dealing with the JavaScript equivalents of primi‐
tive types, these will typically be converted to the appropriate (boxed) types when
they are made visible to Java. For example, if we add the following line to our previ‐
ous example:
System . out . println ( e . get ( "z" ). getClass ());
we can easily see that the value returned by e.get("z") is of type java.lang.Inte
ger . If we change the code very slightly, like this:
n
e . eval ( "i = 27.1;" );
e . put ( "j" , 15 );
e . eval ( "var z = i + j;" );
System . out . println ( e . get ( "z" ). getClass ());
then this is sufficient to alter the type of the return value of e.get("z") to type
java.lang.Double , which marks out the distinction between the two type systems.
In other implementations of JavaScript, these would both be treated as the numeric
type (as JavaScript does not define integer types). Nashorn, however, is more aware
of the actual type of the data.
When dealing wih JavaScript that the Java programmer must
be consciously aware of the difference between Java's static
typing and the dynamic nature of JavaScript types. Bugs can
easily creep in if this awareness is lost.
In our examples, we have made use of the get() and put() methods on the Script
Engine . These allow us to directly get and set objects within the global scope of the
script being executed by a Nashorn engine, without having to write or eval Java‐
Script code directly.
The javax.script API
Let's round out this section with a brief description of some key clases and interfaces
in the javax.script API. This is a fairly small API (six interfaces, five classes, and
one exception) that has not changed since its introduction in Java 6.
ScriptEngineManager
The entry point into the scripting support. It maintains a list of available script‐
ing implementations in this process. This is achieved via Java's service provider
mechanism, which is a very general way of managing extensions to the plat‐
form that may have wildly different implementations. By default, the only
Search WWH ::




Custom Search