Java Reference
In-Depth Information
The following snippet of code creates a Nashorn engine using a class filter, which is
an instance of the
ClassFilter
interface, to restrict the usage of any classes from the
com.jdojo
package and its subpackages. Notice that the
ClassFilter
interface was
added in JDK8u40; it is not available in JDK8:
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine(clsName -> clsName.
startsWith("com.jdojo"));
ClassFilter
is a functional interface. Its method is passed the fully qualified name
of the Java class that the Nashorn script is trying to use. If the method returns
true
, the
class can be used in the script; otherwise, the class cannot be used in the script.
■
If you do not want any Java classes to be exposed in scripts, you can use
clsName
-> false
as the lambda expression for the
ClassFilter
. Using a Java class in the script
that is restricted by the
ClassFilter
throws a
java.lang.ClassNotFound
exception.
Tip
The following is a list of the overloaded versions of the
getScriptEngine()
method
of the
NashornScriptEngineFactory
class:
•
ScriptEngine getScriptEngine()
•
ScriptEngine getScriptEngine(String... args)
•
ScriptEngine getScriptEngine(ClassFilter classFilter)
•
ScriptEngine getScriptEngine(ClassLoader appLoader)
•
ScriptEngine getScriptEngine(String[] args, ClassLoader
appLoader)
•
ScriptEngine getScriptEngine(String[] args, ClassLoader
appLoader, ClassFilter classFilter)
Sharing the Engine Globals
By default, the Nashorn engine maintains the global objects per script context. In this
discussion, the term “globals” means the global variables and declarations stored in the
global scope of the Nashorn script, which you refer to by
this
in the top-level scripts.
Do not mix up the global scope bindings in the script context with the globals in the
script. The script globals are searched first when you reference any variables or create
variables in your script. If you reference a variable in a script that is not found in the script
globals, the engine will search for it in the global scope
bindings
of the script context. For
example, the script objects
Object
,
Math
,
String
, and so on are part of the script globals.
Consider the program and its output in Listing 12-1.
Search WWH ::
Custom Search