Java Reference
In-Depth Information
double x = 15.0;
double y = 10.0;
double addResult = calc.add(x, y);
double subResult = calc.subtract(x, y);
double mulResult = calc.multiply(x, y);
double divResult = calc.divide(x, y);
System.out.printf(
"calc.add(%.2f, %.2f) = %.2f%n",
x, y, addResult);
System.out.printf(
"calc.subtract(%.2f, %.2f) = %.2f%n",
x, y, subResult);
System.out.printf(
"calc.multiply(%.2f, %.2f) = %.2f%n",
x, y, mulResult);
System.out.printf(
"calc.divide(%.2f, %.2f) = %.2f%n",
x, y, divResult);
}
catch (ScriptException e) {
e.printStackTrace();
}
}
}
calc.add(15.00, 10.00) = 25.00
calcr.subtract(15.00, 10.00) = 5.00
calcr.multiply(15.00, 10.00) = 150.00
calc.divide(15.00, 10.00) = 1.50
How did the Nashorn engine find the implementation for the Calculator interface?
When you call the getInterface(Class<T> cls) of Invocable , the engine looks for
compiled functions with the matching names as the abstract methods in the specified
class. In our case, the engine looks for compiled functions named add , subtract ,
multiply , and divide in the engine. Note that it is necessary to call the eval() method of
the engine to compile the functions in the calculatorasfunctions.js file. The Nashorn
engine does not match the number of formal parameters in the Java interface methods
and script functions in the engine.
The second version of the getInterface() method is used to obtain an instance of
a Java interface whose methods are implemented as instance methods of an object. Its
first argument is the reference of the object that is created in the scripting language. The
instance methods of the object implement the interface type passed in as the second
argument. The code in Listing 5-2 creates an object named calculator whose instance
methods implement the Calculator interface. You will the methods of the calculator
object as an implementation of the Calculator interface in Java.
 
Search WWH ::




Custom Search