Java Reference
In-Depth Information
try {
nashorn.eval("function gallons(width, length,
avgDepth){var volume =
avgDepth * width * length;" +
"return volume * 7.48; }");
nashorn.eval("print('Gallons of water in pool: '+
gallons(16,32,5))");
} catch (ScriptException ex) {
Logger.getLogger(NashornInvoker.class.getName()).log(Level.SEVERE,
null, ex);
}
}
}
Results:
run:
Hello Nashorn!
Gallons of water in pool: 19148.800000000003
How It Works
There are many different ways to use the Nashorn engine to execute JavaScript within
a Java application. In this recipe, the example covers two such techniques for doing so,
and each of them requires the use of the ScriptEngineManager, which has been part of
the JDK since Java 6. To obtain a Nashorn engine from the ScriptEngineManager, first
create a new instance of the ScriptEngineManager. Once obtained, you can obtain a
particular engine by passing the string value that represents the desired engine to the
getEngineByName() method. In this case, you pass the name nashorn to obtain
the Nashorn engine for working with JavaScript. After obtaining the Nashorn engine,
you are ready to invoke a JavaScript file or evaluate inline JavaScript code by calling
on the engine's eval() method.
The first code example in this recipe demonstrates how to pass a JavaScript file to
the engine for invocation. The helloNashorn.js in this case contains a single line
of JavaScript that prints a message without returning any results. Perhaps the most dif-
ficult part of executing a .js file is that you must ensure that the file is contained in the
class path, or that you are passing the full path to the file to the eval() method.
Search WWH ::




Custom Search