2011-09-12 42 views
4

,如果我有一個js對象,如以下存儲在js文件我如何可以調用子類屬性的功能,使用Apache犀牛

var _sampleProcessor = { 
    process: function(data){ 
     ... 
    } 

} 

我將如何使用Apache犀牛調用過程中的作用?

// 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."); 
} 

獲取對象的根很容易,但我如何遍歷對象樹的處理功能提前與酒店

回答

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] 
[email protected] 
0.0 
2 
+0

嗨保羅,感謝這麼多的幫助,你的榜樣正是我一直在尋找 – yser77