When I access a member variable of a JavaScript object using Nashorn ScriptObjectMirror.get (), the return type of the object seems to be determined at runtime. For example, if a value fits into a Java int, get () seems to return a Java Integer. If the value does not match int, get () seems to return Java Long, etc.
I am now using instanceof to type check and convert a value to long.
Is there a more convenient way to get a member value without loss and without type checking in Java? Perhaps Nashorn can always give me a Java Double, throwing an error if the member is not numeric.
I can imagine that this is a rather narrow case, which probably should not be handled by Nashorn ...
Example:
package com.tangotangolima.test.nashorn_types;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.StringReader;
public class Main {
public static void main(String[] args) throws ScriptException {
final ScriptEngineManager mgr = new ScriptEngineManager();
final ScriptEngine js = mgr.getEngineByName("nashorn");
final String script = "" +
"var p = 1;" +
"var q = " + (Integer.MAX_VALUE + 1L) + ";" +
"var r = {" +
"s: 1," +
"t: " + (Integer.MAX_VALUE + 1L) +
" };";
js.eval(new StringReader(script));
say(js.get("p").getClass().getName());
say(js.get("q").getClass().getName());
final ScriptObjectMirror r = (ScriptObjectMirror) js.get("r");
say(r.get("s").getClass().getName());
say(r.get("t").getClass().getName());
}
static void say(String s) {
System.out.println(s);
}
}