2010-10-22 7 views
12

aufrufen Ich benutze Mozilla Rhino 1.7r2 (nicht die JDK-Version), und ich möchte eine JS-Funktion von Java aufrufen.Rhino: Wie JS Funktion von Java

Meine JS-Funktion ist wie folgt:

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

Wie kann ich das tun?

Edit: (Die JS-Funktion in einer separaten Datei ist)

+0

http: // www.mozilla.org/rhino/tutorial.html#callingJSfuns –

+0

@org Dieses Beispiel ist mir nicht sehr klar. Wo gebe ich den Pfad der JS-Datei an? Ich gehe davon aus, dass ich einfach den gesamten JS-Code in cmdline eingeben und als Argument an meine Java-App übergeben werde! ^^ " – instantsetsuna

Antwort

33
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: wenn die Funktion im Rahmen geladen wird, zusammen mit anderen Funktionen und Variablen

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

Funktioniert perfekt! Danke! :) Hier ist der vollständige Code http://pastie.org/1240495 – instantsetsuna

+1

Vergessen Sie nicht, dies vor dem Versuch Block context.setOptimizationLevel (-1); – anshad

+0

@Maurice Perry if Ich möchte Funktion mit mehrdimensionalen Integer-Array wie [[1,3], [4,5], [6,9]] dann wie kann ich Object [] übergeben? –

Verwandte Themen