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

问题描述 投票:0回答:1

我希望这是一个简单的问题,但我找不到答案。我使用Map作为将参数传递给Nashorn中的函数的方法。如何在Rhino中将动态构造的对象作为函数参数传递?在任何地方都找不到。例子会很好。我需要传递类似的内容:

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

etc,但在运行时动态创建。我需要将其传递给已编译的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);

我需要将这些动态创建的js对象分配给这些“参数”(例如,分配给params [0]。

java rhino
1个回答
0
投票

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。这是输出。

到这里[对象对象]{this = that}

© www.soinside.com 2019 - 2024. All rights reserved.