Passing undefined to Nashorn Javascript in Scala/Java

女生的网名这么多〃 提交于 2019-12-06 05:48:51

问题


I need to evaluate this function in Javascript from Scala/Java

function hello(a, b) {
    return a+b;
}

I did this basic code:

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

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

I get the expected NaN.

The correct solution would be passing an undefined to the invokeFunction: How do I do this?


回答1:


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


来源:https://stackoverflow.com/questions/30528083/passing-undefined-to-nashorn-javascript-in-scala-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!