如果我有一个js对象,如下面存储在js文件中
var _sampleProcessor = {
process: function(data){
...
}
}
我如何使用Apache Rhino来调用流程函数?
// sb holds the contents of the js file
Context cx = Context.enter();
Scriptable scope = cx.initStandardObjects();
cx.evaluateString(scope, sb.toString(), "Test", 1, null);
Object processor = scope.get("sampleProcessor ", scope);
if (processor == Scriptable.NOT_FOUND) {
System.out.println("processor is not defined.");
}
到达对象的根目录很简单,但如何遍历对象树以获取进程函数属性
提前致谢
答案 0 :(得分:2)
这个例子做了一些事情。像你的例子那样拉出sampleProcessor
,并拉出process
属性并执行该功能。
它还显示了将Java对象添加到作用域中以便可以使用它们 - 示例中的System.out
对象。
package grimbo.test.rhino;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
public class InvokeFunction {
public static void main(String[] args) {
String sb = "var sampleProcessor = {\n" + " process: function(data){\n out.println(0); return 1+1;\n }\n" + "}";
Context cx = Context.enter();
Scriptable scope = cx.initStandardObjects();
Object out = Context.javaToJS(System.out, scope);
ScriptableObject.putProperty(scope, "out", out);
cx.evaluateString(scope, sb.toString(), "Test", 1, null);
// get the sampleProcessor object as a Scriptable
Scriptable processor = (Scriptable) scope.get("sampleProcessor", scope);
System.out.println(processor);
// get the process function as a Function object
Function processFunction = (Function) processor.get("process", processor);
System.out.println(processFunction);
// execute the process function
Object ob = cx.evaluateString(scope, "sampleProcessor.process()", "Execute process", 1, null);
System.out.println(ob);
}
}
输出:
[object Object]
org.mozilla.javascript.gen.Test_1@b169f8
0.0
2