我正在尝试使用 Nashorn 创建 Java 程序的控制台界面。所以我希望根据一些默认导入来评估一些输入。问题是当它访问未定义的值时。理想情况下,engine.eval
应该抛出 ReferenceError
,或返回 null
,但稍后我会得到不一致的值:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Main {
public static void main(String[] args) throws Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
System.out.println(engine.eval("with(JavaImporter(java.util)) { x }"));
System.out.println(engine.eval("with(JavaImporter(java.util)) { x = 1 }"));
System.out.println(engine.eval("with(JavaImporter(java.util)) { x }"));
}
}
ideone 上的结果Windows Oracle JDK 1.8.0_101 是:
null
1
null
最后的输出是 null
,但添加 x == null
会给出 false。
如果我向第一个字符串添加任何空格,我会得到以下输出:
null
1
1
如果第一个和最后一个 engine.eval
参数完全相同(包括空格),则最后一个值似乎为 null
。
x 的值可以在 null
和 1
之间返回,因此它看起来像是引擎中的某种缓存:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Main {
public static void main(String[] args) throws Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
System.out.println(engine.eval("with(JavaImporter(java.util)) { x }"));
System.out.println(engine.eval("with(JavaImporter(java.util)) { x = 1 }"));
System.out.println(engine.eval("with(JavaImporter(java.util)) { x }"));
System.out.println(engine.eval("with(JavaImporter(java.util)) { x }"));
System.out.println(engine.eval("with(JavaImporter(java.util)) { x + x }"));
System.out.println(engine.eval("with(JavaImporter(java.util)) { x }"));
}
}
给予:
null
1
null
1
2.0
null
有什么办法可以让它始终给出 null, 1, 1
结果吗?
最佳答案
强制引擎确认变量的声明。
只需在第一个脚本中使用 var x
即可。
System.out.println(engine.eval("with(JavaImporter(java.util)) { var x }"));
System.out.println(engine.eval("with(JavaImporter(java.util)) { x = 1 }"));
System.out.println(engine.eval("with(JavaImporter(java.util)) { x }"));
关于java - 访问未定义值后 Nashorn 中的输出不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39046775/