Java Reference
In-Depth Information
Using the Anonymous Class-Like Syntax
This method uses a syntax that is very similar to the syntax of creating an anonymous
class in Java. The following statement implements the Java Calculator interface and
creates an instance of that implementation:
// Get the Java interface type
var Calculator = Java.type("com.jdojo.script.Calculator");
// Create an instance of the com.jdojo.script.Calculator interface
// using an anonymous class-like syntax
var calc = new Calculator() {
add: (function (n1, n2) n1 + n2),
subtract: (function (n1, n2) n1 - n2),
multiply: (function (n1, n2) n1 * n2),
divide: (function (n1, n2) n1 / n2)
};
Now you can use the calc object the same way as you did before.
Using the JavaAdapter Object
JavaScript lets you implement multiple interfaces and extend a class using the
JavaAdapter class. However, the Rhino JavaScript implementation that is bundled
with JDK has overridden the implementation of JavaAdapter , which allows you to
implement only one interface; it does not let you extend a class. The first argument to the
JavaAdapter constructor is the interface to implement and the second argument is the
script object that implements the interface's abstract methods. To use the JavaAdapter
object in Nashorn, you need to load the Rhino compatibility module. The following
snippet of code implements the Calculator interface using JavaAdapter :
// Need to load the compatibility module in Nashorn.
// You do not need to the following load() call in Rhino.
load("nashorn:mozilla_compat.js");
// Load the script that creates the calculator JavaScript object
load("calculator.js");
var calc = new JavaAdapter(com.jdojo.script.Calculator, calculator);
Now you can use the calc object the same way as you did before. It is an instance of
the com.jdojo.script.Calculator interface whose implementation has been provided
by the methods declared in the calculator object as defined in script in the
calculator.js file.
 
Search WWH ::




Custom Search