import java.util.HashMap;
import java.util.Map;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import junit.framework.TestCase;
public class ScriptEngineTest extends TestCase {
public void testNull() throws ScriptException {
Map globals = new HashMap();
javax.script.ScriptEngineManager manager = new
javax.script.ScriptEngineManager();
ScriptEngine engine = manager.getEngineByExtension("js");
Object o = engine.eval("var city = null; city;");
assertNull(o);
}
}
I would expect the returned object 'o' to be null. Unfortunately,
engine.eval always throws the following error:
org.mozilla.javascript.EcmaError: ReferenceError: "city" is not
defined. (<Unknown source>#1)
at
org.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:
3350)
at
org.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:
3340)
at
org.mozilla.javascript.ScriptRuntime.notFoundError(ScriptRuntime.java:
3413)
What am I doing wrong? When I run this same statement through
Firefox's Error Console, it returns null as I would expect.
I'm using the Scripting JSR libraries because I'm running under Java
5, not Java 6. Other statements evaluate as I would expect, the only
problems seem to occur with null values. I've tried the code with
js-1.6R5 that comes with the JSR libraries and I've also tried
upgrading to js-1.6R7. The result is the same.
Help! Its driving me nuts. I need to have nullable values.
-Tom
Perhaps it is a problem with the javax.script package. When I try the
equivalent with Rhino APIs, it works as expected:
[rhino] cat RunScript.java
import org.mozilla.javascript.*;
public class RunScript {
public static void main(String args[])
{
Context cx = Context.enter();
try {
Scriptable scope = cx.initStandardObjects();
Object result = cx.evaluateString(scope, "var city = null;
city;",
"<cmd>", 1, null);
System.err.println(Context.toString(result));
} finally {
Context.exit();
}
}
}
[rhino] javac -classpath build/rhino1_7R1pre/js.jar RunScript.java
Note: RunScript.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
[rhino] java -classpath build/rhino1_7R1pre/js.jar:. RunScript
null
--N
Norris, thank you for trying that out for me. I discovered the cause
I really had to search for this, but I found one other reference to
this same problem at http://www.cosmocode.de/en/blogs/detman/20060620161531/.
In further digging it turned out that I was using an early
implementation of the JSR223 (javax.script.Bindings was called
javax.script.Namespace). I downloaded the final implementation of the
JSR at http://jcp.org/aboutJava/communityprocess/final/jsr223/index.html
and plugged that in and everything works as expected. The problem
must have been in the first JSR223 wrapper around Rhino. I was
unaware that there was a difference.