gpt4 book ai didi

javascript - 在 Nashorn 中将 javascript 名称设置为 Java 函数

转载 作者:行者123 更新时间:2023-11-29 21:41:42 25 4
gpt4 key购买 nike

我想为 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() 需要一个对象,而 lambda 不是对象。如何将 javascript 名称设置为 java 函数?

编辑澄清:

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

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

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

最佳答案

感谢@Seelenvirtuose,事实证明您只需将它设置为 Consumer(或任何其他功能接口(interface)),然后 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);
}
}

编辑:我整理了一个很小的零依赖库,用于将 lambda 表达式传递给脚本: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);
}

关于javascript - 在 Nashorn 中将 javascript 名称设置为 Java 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32596733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com