在Scala / Java中将undefined传递给Nashorn Javascript [英] Passing undefined to Nashorn Javascript in Scala/Java
问题描述
我需要在Scala / Java的Javascript中评估这个函数
I need to evaluate this function in Javascript from Scala/Java
function hello(a, b) {
return a+b;
}
我做了这个基本代码:
val factory = new ScriptEngineManager(null)
val engine = factory.getEngineByName("JavaScript")
val body =
"""
|function hello(a, b) {
| return a+b;
|}
""".stripMargin
engine match {
case engine: Invocable =>
engine.eval(body)
println(engine.invokeFunction("hello", null, 1: java.lang.Double))
}
对于参数a,我传递的是null,结果得到1.0。如果我破解了我的javascript(我不想做这个)而且我做到了:
For the parameter a I'm passing a null and I get a 1.0 as a result. If I hack my javascript (I DON'T WONT TO DO THIS) and I make it:
function hello(a, b) {
if (a === null) {
a = undefined;
}
return a+b;
}
我得到预期的NaN。
正确的解决方案是将undefined传递给invokeFunction:
我该怎么做?
The correct solution would be passing an undefined to the invokeFunction: How do I do this?
推荐答案
ScriptEngine.eval将undefined转换为null - 因为Java中没有undefined的概念。如果你想获得内部nashorn未定义对象并传递它(为什么?),你可以这样做:
ScriptEngine.eval translates undefined to null - as there is no concept of undefined in Java. If you do want to get internal nashorn undefined object and pass it around (why?), you can do something like this:
import javax.script.*;
public class Test {
private static Object undefined;
public static void main(String[] args) throws Exception {
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine e = m.getEngineByName("nashorn");
e.eval("Packages.Test.setUndefined(undefined)");
e.eval("function func(a, b) { return a + b; }");
Object val = ((Invocable)e).invokeFunction("func", undefined, 44);
if (val instanceof Double && ((Double)val).isNaN()) {
System.out.println("got NaN as expected");
}
}
public static void setUndefined(Object obj) {
undefined = obj;
}
}
这篇关于在Scala / Java中将undefined传递给Nashorn Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!