ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java – 如何使用Apache Rhino调用子属性函数

2019-07-04 17:44:30  阅读:167  来源: 互联网

标签:java javascript rhino mozilla


如果我有一个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.");
}

到达对象的根目录很容易,但是如何遍历对象树以获取进程函数属性

提前致谢

解决方法:

这个例子做了一些事情.像你的例子那样拉出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

标签:java,javascript,rhino,mozilla
来源: https://codeday.me/bug/20190704/1379446.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有