Java Reference
In-Depth Information
Invoking Script Functions From Java
You can invoke script functions from Java code. The Java code may be passed the script
function object from the script or it may obtain the reference of the function object
through the script engine. You can use the call() method on a ScriptObjectMirror that
is the reference of the function object. The method's declaration is:
Object call(Object thiz, Object... args)
The first argument is the object reference that is used as this in the function
invocation. The second argument is the list of arguments passed to the function. To
invoke the function in the global scope, use null as the first argument.
In Chapter 4, you created a factorial() function to compute the factorial of a
number. The declaration of this function is shown in Listing 12-8.
Listing 12-8. The Declaration of the factorial() Function
// factorial.js
// Returns true if n is an integer. Otherwise, returns false.
function isInteger(n) {
return typeof n === "number" && isFinite(n) && n%1 === 0;
}
// Define a function that computes and returns the factorial of an integer
function factorial(n) {
if (!isInteger(n)) {
throw new TypeError("The number must be an integer. Found:" + n);
}
if(n < 0) {
throw new RangeError("The number must be greater than 0. Found: " + n);
}
var fact = 1;
for(var counter = n; counter > 1; fact *= counter--);
return fact;
}
Listing 12-9 contains the Java program that loads the script from the factorial.js
file, obtains the reference of the factorial() function in a ScriptObjectMirror , uses
the call() method to call the factorial() function, and prints the result. At the end, the
program calls the Array.prototype.join() function on a String object using the call()
method of the ScriptObjectMirror class.
 
Search WWH ::




Custom Search