Java Nashorn不一致的绑定行为。这是一个错误吗?

时间:2015-09-15 11:54:02

标签: java nashorn

Nashorn没有以一致的方式处理绑定。我怀疑这是一个错误,但我想这可能是一些优化副作用。

可以使用简单的测试用例重现不一致的行为:

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();
  }  
}

运行此程序时,它会产生以下输出:

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"

因此前7次迭代按预期工作,但突然发生了一些事情,使得scriptengine将DataA评估为未定义而不是抛出异常。

这是一个错误吗?

2 个答案:

答案 0 :(得分:2)

是的,这是一个错误。我提交了https://bugs.openjdk.java.net/browse/JDK-8136544来跟踪它。

答案 1 :(得分:0)