【问题标题】:Set a javascript name to be a Java function in Nashorn在 Nashorn 中将 javascript 名称设置为 Java 函数
【发布时间】:2015-09-15 22:28:00
【问题描述】:

我想为 Nashorn 提供一个函数,如下所示:

public class StackOverflow {
    private Object toSave;

    @Test
    public void test() {
        ScriptEngine jsEngine = new ScriptEngineManager().getEngineByName("nashorn");
        ScriptContext context = jsEngine.getContext();
        context.setAttribute("saveValue", arg -> { toSave = arg; }, ScriptContext.ENGINE_SCOPE);
        jsEngine.eval("saveValue('one')");
        Assert.assertEquals("one", toSave);
    }
}

上面的代码无法编译,因为ScriptContext.setAttribute() 需要一个对象,而 lambdas 不是对象。如何将 javascript 名称设置为 java 函数?

编辑澄清:

在 JavaScript 中,我们可以这样写:

var square = function(y) {
   return y * y;
};
square(9);

如果我用 Java 编写了 square,我如何将该函数分配给 JavaScript 变量?

【问题讨论】:

  • 由于 lambda 表达式 arg -> { toSave = arg; } 显然是 Consumer,我建议将其放入该类型的变量中,并在调用 @987654328 时使用此变量(而不是 lambda 本身) @.
  • 您要解决的具体问题是什么?您不能将 lambda 表达式设置为 JavaScript 引擎的属性。

标签: javascript java java-8 nashorn


【解决方案1】:

感谢@Seelenvirtuose,事实证明您可以将其设置为Consumer(或任何其他功能接口),然后Nashorn 会做正确的事情。下面的测试通过了。

public class StackOverflow {
    private Object toSave;

    @Test
    public void test() throws ScriptException {
        Consumer<String> saveValue = obj -> toSave = obj;
        ScriptEngine jsEngine = new ScriptEngineManager().getEngineByName("nashorn");
        ScriptContext context = jsEngine.getContext();
        context.setAttribute("saveValue", saveValue, ScriptContext.ENGINE_SCOPE);
        jsEngine.eval("saveValue('one')");
        Assert.assertEquals("one", toSave);
    }
}

编辑:我整理了一个很小的零依赖库,用于将 lambdas 传递给脚本:JScriptBox。帮助了我,也许它会帮助你。

private int square(int x) {
    return x * x;
}

@Test
public void example() throws ScriptException {
    TypedScriptEngine engine = JScriptBox.create()
        .set("square").toFunc1(this::square)
        .set("x").toValue(9)
        .buildTyped(Nashorn.language());
    int squareOfX = engine.eval("square(x)", Integer.class);
    Assert.assertEquals(81, squareOfX);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多