【发布时间】:2016-03-10 15:06:11
【问题描述】:
我一直在尝试使用 Nashorn,并得到了一些关于 eval() 的返回类型的奇怪结果。
// calculator.js
var add = function(a, b) {
return a + b;
}
还有以下 Java 代码:
// CalculatorTest.java
import java.io.InputStreamReader;
import javax.script.*
import org.junit.*
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
public class CalculatorTest {
ScriptEngine nashorn;
@Before
public void setup() throws ScriptException {
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
nashorn = factory.getScriptEngine("–optimistic-types=true");
nashorn.eval(new InputStreamReader(
getClass().getClassLoader().getResourceAsStream("calculator.js")));
}
@Test
public void addViaInvokeFuntion() throws Exception {
Object result = ((Invocable) nashorn).invokeFunction("add", 2, 3);
Assert.assertEquals(5.0, result);
}
@Test
public void addViaSimple() throws Exception {
Object result = nashorn.eval("2+3");
Assert.assertEquals(5, result);
}
@Test
public void addViaMoreComplexEval() throws Exception {
Object result = nashorn.eval(
"var anotherAdd = function(a, b) {\n" +
" return a + b;\n" +
"};\n" +
"anotherAdd(2, 3);");
Assert.assertEquals(5L, result);
}
}
为什么这些测试会以这种方式成功?
有没有办法“预测” Nashorn 返回类型?
乐观类型不应该这样做吗?
【问题讨论】:
-
当我和迈克尔一起偶然发现这个问题时,我支持这个问题。更准确地说:如果直接使用
eval()调用操作或函数,为什么会返回Integer,如果从外部js 文件调用函数,为什么会返回Double?我完全清楚,应该使用Number并且在 JS 中,一切都是浮动的。但除此之外,为什么一次返回Integer而另一次返回Double?
标签: javascript java nashorn