问题
I'm running this code
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval("var out;");
engine.eval("var out1 = null;");
Object m = engine.get("out");
Object m1 = engine.get("out1");
And getting m == null and m1 == null.
How to determine if value is undefined or null?
回答1:
Java doesn't have a concept of "undefined", so understanding the distinction will require expressing it in the script's language. I suggest using this expression:
Boolean isUndefined = engine.eval("out === undefined");
回答2:
Actually, the correct way to know if the Object returned by the script is undefined
is by asking ScriptObjectMirror
:
import jdk.nashorn.api.scripting.ScriptObjectMirror;
Object m = engine.get("out");
if (ScriptObjectMirror.isUndefined(m)) {
System.out.println("m is undefined");
}
Alternative way, using Nashorn internal API
You can also do it by checking its type:
import jdk.nashorn.internal.runtime.Undefined;
Object m = engine.get("out");
if (m instanceof Undefined) {
System.out.println("m is undefined");
}
Notice that Nashorn did not make the Undefined
type part of the public API, so using it can be problematic (they are free to change this between releases), so use ScriptObjectMirror
instead. Just added this here as a curiosity...
回答3:
I'd check
engine.eval("typeof out")
which will be "undefined" and
engine.eval("typeof out1")
would be "object"
来源:https://stackoverflow.com/questions/29277606/differ-null-and-undefined-values-in-nashorn