When passing variables from Java to JavaScript (Nashorn) using the
javax.script.Bindings API, variables of Long type are not always mapped to a
JavaScript number. In some cases they shows up as a plain JavaScript Object
instead.
This happens if the javax.script.Bindings object already contains a variable
of the same name.
STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
1) Pass a Long variable to JavaScript via javax.script.Bindings API
2) Verify the type in the JavaScript end by evaluating "typeof". Should
correctly return "number"
3) Pass a new Long value for the same variables via javax.script.Bindings API
4) Verify the type in the JavaScript end again. Should correctly return
"number", but returns "object" now.
EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
Data type of passed variable should always be "number".
Attached test case SHOULD produce the following printout:
undefined
number
number
ACTUAL -
Datatype but is now "object" instead"
Attached test case PRODUCES the following printout instead:
undefined
number
object
REPRODUCIBILITY :
This bug can be reproduced always.
---------- BEGIN SOURCE ----------
import javax.script.*;
public class JavaScriptTest {
ScriptEngine engine;
Bindings bindings;
public JavaScriptTest() throws ScriptException {
ScriptEngineManager mgr = new ScriptEngineManager();
engine = mgr.getEngineByName("javascript");
bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
testType();
bindings.put("fileSize", new Long(1000000000L));
testType();
bindings.put("fileSize", new Long(2000000000L));
testType();
}
public void testType() throws ScriptException {
engine.eval("print(typeof fileSize);");
}
public static void main(String[] args) throws ScriptException {
new JavaScriptTest();
}
}