Rhino, typeof and autoboxing confusion
-
27-09-2019 - |
문제
In a server side extension for SmartfoxServer (which uses Rhino) I had a piece of Javascript similar to this:
response["xpos"] = properties.get("xpos");
send(JSON.stringify(response));
This caused errors. What happened? Because properties is a Java Map
, when a number is put into it, it's autoboxed into a java.lang.Double
object. Therefore, when retrieving it and storing it in response["xpos"]
, the result is not a regular Javascript number but a JavaObject
of type java.lang.Double
. The JSON.stringify
function was not meant to handle that and it crashed.
I fixed it with a hack like this:
response["xpos"] = 1.0 * properties.get("xpos");
send(JSON.stringify(response));
Is there a better way?
해결책
You can use Number(properties.get("xpos"))
, as in the following interactive console session:
js> x=java.lang.Double(2)
2.0
js> typeof x
object
js> x instanceof java.lang.Double
true
js> y=Number(x)
2
js> typeof y
number
This is how strings are typically converted in Rhino from java.lang.String to native JavaScript strings as well.