Picking up where I left off in the previous post, I am going to cover some ways to get data into a script.
Here’s how to simply supply parameter values when calling a function defined in a script. First the ScriptRunner needs to be updated:
pubic class ScriptRunner {
...
public void load(String scriptName) throws ... {
Reader reader = resourceReader(scriptName);
_engine.eval(reader);
}
public <T> T invoke(String functionName, Object... params) throws ... {
//noinspection unchecked
return (T) ((Invocable) _engine).invokeFunction(functionName, params);
}
private InputStreamReader resourceReader(String scriptName) {
InputStream stream = getClass().getResourceAsStream(scriptName);
return new InputStreamReader(stream);
}
}
Now, given some script:
// userdef.js
function expectedSalesTax(productType, unitPrice, quantity) {
return unitPrice * quantity * 0.0825; // 8.25%
}
It can be invoked after the script is loaded:
ScriptRunner runner = new ScriptRunner();
runner.load("userdef.js");
double taxes = runner.invoke("expectedSalesTax", "sneakers", 99.90, 5);
Advertisement
Trackbacks
[...] my previous post, I showed how the parameters to a JavaScript can be supplied with Java. The next step is to supply [...]