2010-10-22 37 views
12

我正在使用Mozilla Rhino 1.7r2(不是JDK版本),我想從Java調用JS函數。犀牛:如何從Java調用JS函數

我的JS函數是這樣的:

function abc(x,y) 
{ 
    return x+y 
} 

我該怎麼辦呢?

編輯:(本JS功能是在一個單獨的文件)

+0

HTTP沿着:// www.mozilla.org/rhino/tutorial.html#callingJSfuns – 2010-10-22 10:47:51

+0

@org這個例子對我來說不是很清楚。我在哪裏指定JS文件的路徑?我想它假定我只需在cmdline中輸入完整的JS代碼並將其作爲arg傳遞給我的java應用程序! ^^「 – instantsetsuna 2010-10-22 11:03:37

回答

33
String script = "function abc(x,y) {return x+y;}"; 
Context context = Context.enter(); 
try { 
    ScriptableObject scope = context.initStandardObjects(); 
    Scriptable that = context.newObject(scope); 
    Function fct = context.compileFunction(scope, script, "script", 1, null); 
    Object result = fct.call(
      context, scope, that, new Object[] {2, 3}); 
    System.out.println(Context.jsToJava(result, int.class)); 
} finally { 
    Context.exit(); 
} 

UPDATE:當功能被裝載在的範圍內,與其他函數和變量

String script = "function abc(x,y) {return x+y;}" 
     + "function def(u,v) {return u-v;}"; 
Context context = Context.enter(); 
try { 
    ScriptableObject scope = context.initStandardObjects(); 
    context.evaluateString(scope, script, "script", 1, null); 
    Function fct = (Function)scope.get("abc", scope); 
    Object result = fct.call(
      context, scope, scope, new Object[] {2, 3}); 
    System.out.println(Context.jsToJava(result, int.class)); 
} finally { 
    Context.exit(); 
} 
+0

完美地工作!謝謝!:)下面是完整的代碼http://pastie.org/1240495 – instantsetsuna 2010-10-22 12:02:18

+1

不要忘記在嘗試之前添加此塊context.setOptimizationLevel(-1); – anshad 2016-04-06 12:28:40

+0

@Maurice Perry if我想調用像[[1,3],[4,5],[6,9]]這樣的多維整數數組的函數,那麼我怎麼能通過對象[]? – 2016-08-11 15:58:58