Rhino: How to call JS function from Java

匿名 (未验证) 提交于 2019-12-03 01:55:01

问题:

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

My JS function is like this:

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

How do I do this?

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

回答1:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!