I have an instance of this Java class accessible in my Javascript program
public class ContentProvider {
public Object c(int n) {
switch (n) {
case 1: return 1.1;
case 2: return 2.2;
case 3: return 3.3;
case 4: return "4";
case 5: return new java.util.Date();
}
return null;
}
}
This is the code inside main():
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
engine.put("ctx", new ContentProvider());
res = engine.eval("ctx.c(1)");
System.out.printf("rhino:> %s (%s)%n"
, res
, res != null ? res.getClass().getName() : null
);
The simple expression ctx.c(1)
prints:
rhino:> 1.1 (java.lang.Double)
Now here is what happens with ctx.c(1) + ctx.c(2)
:
rhino:> 1.12.2 (java.lang.String)
And finally (ctx.c(1) + ctx.c(2)) * ctx.c(3)
:
rhino:> nan (java.lang.Double)
Rhino is performing string concatenation instead of number arithmetics! The following program works as expected instead:
engine.put("a", 1.1);
engine.put("b", 2.2);
engine.put("c", 3.3);
res = engine.eval("(a + b) * c");
Outputs:
rhino:> 10,89 (java.lang.Double)
engine.eval("typeof ctx.c(1)")
and see what JavaScript thinks the type is? – Wismar