Java Reference
In-Depth Information
Listing 5-5. The Contents of the calculatorasfunctions.js File
// calculatorasfunctions.js
function add(n1, n2) {
n1 + n2;
}
function subtract(n1, n2) {
n1 - n2;
}
function multiply(n1, n2) {
n1 * n2;
}
function divide(n1, n2) {
n1 / n2;
}
These two functions provide the implementations for the four methods of the
Calculator interface. After the functions are compiled by a JavaScript engine, you can
obtain an instance of the Calculator interface, as shown:
// Cast the engine reference to the Invocable type
Invocable inv = (Invocable)engine;
// Get the reference of the Calculator interface
Calculator calc = inv.getInterface(Calculator.class);
if (calc == null) {
System.err.println("Calculator interface implementation not found.");
}
else {
// Use calc to call the methods of the Calculator interface
}
You can add two numbers, as shown:
int sum = calc.add(15, 10);
Listing 5-6 shows how to implement a Java interface using top-level procedures in
Nashorn. Please consult the documentation of a scripting language (other than Nashorn)
to learn how it supports this functionality.
 
Search WWH ::




Custom Search