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

标签 java rhino

我希望这是一个简单的问题,但我找不到答案。我使用 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/

相关文章:

javascript - 从 rhino 中的 orientDB 选择

java - 为什么 java newInstance 卡在 getDeclaredConstructors0 处?

java - 为什么 Java 反射调用比方法调用快?

java - 为什么会出现这个异常呢? Lucene异常

java - 未注解的方法会覆盖使用@NotNull 注解的方法

Java 对象到 JSON

Rhino 解释器中的 JavaScript - 函数返回未定义

java - 如何编写使用 * 打印大写字母 F 的嵌套循环

java - 如何通过Internet发送数据报包?

java - 在 Java 和 (Rhino) Javascript 之间传递通用类型