javascript Rhino:如何从 Java 调用 JS 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3995897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:06:17  来源:igfitidea点击:

Rhino: How to call JS function from Java

javajavascriptrhino

提问by instantsetsuna

I'm using Mozilla Rhino 1.7r2 (not the JDK version), and I want to call a JS function from Java.

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

My JS function is like this:

我的JS函数是这样的:

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

How do I do this?

我该怎么做呢?

Edit: (The JS function is in a separate file)

编辑:(JS 函数在一个单独的文件中)

回答by Maurice Perry

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: when the function is loaded in the scope, along with other functions and variables

更新:当函数与其他函数和变量一起加载到作用域中时

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