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

Mozilla Rhino :如何从Java调用JS函数,第1张

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

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


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5586545.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-14
下一篇2022-12-14

发表评论

登录后才能评论

评论列表(0条)

    保存