[英]Java Nashorn inconsistent binding behavior. Is this a bug?
Nashorn doesn't handle bindings in a consistent way. Nashorn不会以一致的方式处理绑定。 I suspect it's a bug but I guess it might be some optimization side effect. 我怀疑这是一个错误,但我想这可能是一些优化副作用。
The inconsistent behaviour can be reproduced with a simple test case: 可以使用简单的测试用例重现不一致的行为:
package jsbugtest;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class JsBugTest {
public static Object resolve(ScriptEngine engine, String script) {
Object r = null;
try {
r = engine.eval(script);
} catch (Exception ex) {
System.out.println("exception: " + ex.getMessage());
r = null;
}
return r;
}
public static void runTest()
{
ScriptEngineManager mgr = new ScriptEngineManager(null);
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
String script = "DataA + 'foo';";
Bindings binds = jsEngine.getBindings(ScriptContext.ENGINE_SCOPE);
Object ret;
for (int i = 0; i < 12; i++) {
binds.remove("DataA");
ret = resolve(jsEngine, script);
if (ret != null) {
System.out.println("Iteration " + i + ": Returned value should be null but is: \"" + ret + "\"");
}
binds.put("DataA", "foo");
ret = resolve(jsEngine, script);
if (ret == null) {
System.out.println("Iteration " + i + " failed");
}
}
}
public static void main(String[] args) {
JsBugTest.runTest();
}
}
When running this program it produces the following output: 运行此程序时,它会生成以下输出:
exception: ReferenceError: "DataA" is not defined in <eval> at line number 1
exception: ReferenceError: "DataA" is not defined in <eval> at line number 1
exception: ReferenceError: "DataA" is not defined in <eval> at line number 1
exception: ReferenceError: "DataA" is not defined in <eval> at line number 1
exception: ReferenceError: "DataA" is not defined in <eval> at line number 1
exception: ReferenceError: "DataA" is not defined in <eval> at line number 1
exception: ReferenceError: "DataA" is not defined in <eval> at line number 1
exception: ReferenceError: "DataA" is not defined in <eval> at line number 1
Iteration 8: Returned value should be null but is: "undefinedfoo"
Iteration 9: Returned value should be null but is: "undefinedfoo"
Iteration 10: Returned value should be null but is: "undefinedfoo"
Iteration 11: Returned value should be null but is: "undefinedfoo"
So the first 7 iterations works as expected but then suddenly something happens that makes scriptengine evaluate DataA to undefined instead of throwing an exception. 因此前7次迭代按预期工作,但突然发生了一些事情,使得scriptengine将DataA评估为未定义而不是抛出异常。
Is this a bug? 这是一个错误吗?
Yep, it's a bug. 是的,这是一个错误。 I filed https://bugs.openjdk.java.net/browse/JDK-8136544 to keep track of it. 我提交了https://bugs.openjdk.java.net/browse/JDK-8136544来跟踪它。
And this bug has been fixed in jdk9 and backported to jdk8u 这个bug已在jdk9中修复并向后移植到jdk8u
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.