Java Reference
In-Depth Information
use the Invocable interface to execute procedures, functions, and methods
repeatedly. evaluation of the script, having procedures, functions, and methods, stores the
intermediate code in the engine that results in performance gain on their repeated execution.
Tip
Implementing Java Interfaces in Scripts
The Java Scripting API lets you implement Java interfaces in a scripting language. The
advantage of implementing a Java interface in a scripting language is that you can use
instances of the interface in Java code as if the interface was implemented in Java. You
can pass instances of the interface as arguments to Java methods. Methods of the Java
interface may be implemented in scripts using top-level procedures or methods of an
object.
The getInterface() method of the Invocable interface is used to obtain the
instances of a Java interface that is implemented in scripts. The method has two versions:
<T> T getInterface(Class<T> cls)
<T> T getInterface(Object obj, Class<T> cls)
The first version is used to obtain an instance of a Java interface whose methods
are implemented as top-level procedures in scripts. The interface type is passed to this
method as its argument. Suppose that you have a Calculator interface, as declared
in Listing 5-4, that contains four methods called add() , subtract() , multiply() and
divide() .
Listing 5-4. A Calculator Interface
// Calculator.java
package com.jdojo.script;
public interface Calculator {
double add (double n1, double n2);
double subtract (double n1, double n2);
double multiply (double n1, double n2);
double divide (double n1, double n2);
}
Consider the top-level functions written in Nashorn as shown in Listing 5-5. The
script contains four functions that correspond to the functions in the Calculator
interface.
 
 
Search WWH ::




Custom Search