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: khi hàm được nạp trong phạm vi, cùng với các chức năng khác và các biến
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();
}
Nguồn
2010-10-22 10:57:09
http: // www.mozilla.org/rhino/tutorial.html#callingJSfuns –
@org Ví dụ đó không rõ ràng đối với tôi. Tôi chỉ định đường dẫn của tệp JS ở đâu? Tôi đoán nó giả định rằng tôi chỉ cần gõ toàn bộ mã JS trong cmdline và chuyển nó như là một arg cho ứng dụng java của tôi! ^^ " – instantsetsuna