Rhino:如何从Java调用JS函数

时间:2010-10-22 10:21:43

标签: java javascript rhino

我正在使用Mozilla Rhino 1.7r2(不是JDK版本),我想从Java调用JS函数。

我的JS功能是这样的:

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

我该怎么做?

编辑:( JS功能在一个单独的文件中)

1 个答案:

答案 0 :(得分:34)

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();
}

更新:当函数在范围内加载时,以及其他函数和变量

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();
}