Java Reference
In-Depth Information
else if (name === "subtract")
value = args[0] - args[1];
else if (name === "multiply")
value = args[0] * args[1];
else if (name === "divide")
value = args[0] / args[1];
else
throw new Error("Operation " + name +
" not supported.");
return value;
}
};
var calc = new JSInvoker(calcDelegate);
var x = 20.44, y = 30.56;
var addResult = calc.add(x, y); // Will call calcDelegate.invoke("add", [x, y])
var subResult = calc.subtract(x, y);
var mulResult = calc.multiply(x, y);
var divResult = calc.divide(x, y);
printf("calc.add(%.2f, %.2f) = %.2f%n", x, y, addResult);
printf("calc.sub(%.2f, %.2f) = %.2f%n", x, y, subResult);
printf("calc.mul(%.2f, %.2f) = %.2f%n", x, y, mulResult);
printf("calc.div(%.2f, %.2f) = %.2f", x, y, divResult);
The code creates an object named calcDelegate that contains an invoke() method.
The JSInvoker object wraps the calcDelegate object. When a function is called on the
calc object, the invoke() method of the calcDelegate object is called with the function
name as its first argument and function arguments passed as an array as the second
argument. The invoke() function performs addition, subtraction, multiplication, and
division on the arguments. The following command shows how to execute the code:
c:\>jrunscript -f jsinvokertest.js
calc.add(20.44, 30.56) = 51.00
calc.sub(20.44, 30.56) = -10.12
calc.mul(20.44, 30.56) = 624.65
calc.div(20.44, 30.56) = 0.67
The JSInvoker object works in Java 7 but generates the following error in Java 8
when you run this example. It seems to be a bug introduced in Java 8:
c:\>jrunscript -f jsinvokertest.js
script error in file jsinvoker.js : TypeError: [object JSAdapter] has no
such function "add" in jsinvoker.js at line number 25
Search WWH ::




Custom Search