gpt4 book ai didi

java - 使用Rhino将动态构造的对象作为参数传递给JS函数

转载 作者:行者123 更新时间:2023-12-01 17:47:01 25 4
gpt4 key购买 nike

我希望这是一个简单的问题,但我找不到答案。我使用 Map 作为向 Nashorn 中的函数传递参数的方式。如何在 Rhino 中将动态构造的对象作为函数参数传递?到处都找不到它。例子就太好了。我需要传递类似的东西:

{
field1: "value1",
field2: 2,
someotherField: "another"
}

等,但在运行时动态创建。我需要将它传递给编译后的 js 函数,如下所示:

String src="function fooname(params) {\n"+
" for(var key in params)\n" +
" {\n" +
" print(key+\" : \"+params[key])\n" +
" }\n" +
"}\n";
Context context = Context.enter();
Script script = context.compileString(src, "testSource", 0, null);
script.exec(context, scope);
Function foo = (Function) scope.get("fooName", scope);
foo.call(context, scope, scope, params);

我需要为这些“params”(例如 params[0])分配一个动态创建的 js 对象。

最佳答案

Context 类为此提供了一些很棒的选项。这是一个示例,我使用两种不同的方法来完成创建函数。

public static void main(String[] args){
String funCode = "function(arg){ print(arg);}";
String funName = "checkPlease";
String objCode = "x = { one : 1, two : \"two\"};";
Context context = Context.enter();
Scriptable scope = context.initStandardObjects();
context.evaluateString(scope, "function print( arg ){Packages.java.lang.System.out.println( arg );};", null, 1, null);
context.evaluateString(scope, "print(\"to here\")", null, 1, null);

Function fun = context.compileFunction( scope, funCode, funName, 1, null);
Script s = context.compileString(objCode, "NA", 1, null);
Object obj = s.exec(context, scope);
fun.call(context, scope, fun, new Object[]{ obj});
HashMap<String, String> map = new HashMap<>();
map.put("this", "that");
fun.call(context, scope, fun, new Object[]{ context.javaToJS(map, scope) });
}

由于 print 没有进入我的范围,我只是使用评估字符串创建了一个函数。我还使用compileFunction 创建了一个函数。我调用该函数并以三种不同的方式传递参数。 A) 只是从 javascript 调用 javascript 函数。 B) 编译字符串并将其作为参数传递,C) 使用 context.javaToJS。这是输出。

to here
[object Object]
{this=that}

关于java - 使用Rhino将动态构造的对象作为参数传递给JS函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60852422/

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