Java Reference
In-Depth Information
jjs -scripting
jjs> "The current date is ${Date()}"
The current date is Wed Apr 30 2014 23:44:41 GMT-0500
(CDT)
Note
If you're not using the scripting features of jjs, string interpolation will not be
available. Also, double quotes must be placed around the string of text, as strings in
single quotes are not interpolated. In the example, the shebang (
#! usr/bin/env
) is
used to make the script executable, thereby invoking the scripting features of
jjs
.
18-4. Passing Java Parameters
Problem
You want to pass Java parameters to JavaScript for use.
Solution
Utilize a
javax.script.SimpleBindings
instance to provide a string-based
name for any Java field, and then pass the
SimpleBindings
instance to the
JavaScript engine invocation. In the following example, a Java string parameter is
passed to the Nashorn engine, and then it's printed via JavaScript.
String myJavaString = "This is a Java parameter!";
SimpleBindings simpleBindings = new SimpleBindings();
simpleBindings.put("myString", myJavaString);
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine nashorn = sem.getEngineByName("nashorn");
nashorn.eval("print (myString)", simpleBindings);
Here is the result:
This is a Java parameter!