2012-07-17 100 views
3

我正在使用Rhino。和做從評估的JS獲取函數名稱及其參數Rhino

Context cx = Context.enter(); 
Scriptable scope = cx.initStandardObjects(); 
cx.evaluateString(scope, "function f(x,y){ return x+y}", "<cmd>", 1, null); 

後,我想知道,有一個名爲f和兩個參數xy 功能,但找不到任何方法可以幫助我這一點。

+0

看起來像我需要使用解析器類從犀牛。它實現了我需要的一切。 – 2012-07-17 04:49:40

+0

查看http://stackoverflow.com/questions/12108447/get-variables-from-javascript-expression-rhino – 2013-02-05 00:45:28

回答

0

嘗試使用下一個代碼。

package com.qarea.rhinotest; 

import org.mozilla.javascript.Context; 
import org.mozilla.javascript.Scriptable; 

public class RhinoTest { 

    public static void main(String[] args) { 
     Context cx = Context.enter(); 
     Scriptable scope = cx.initStandardObjects(); 
     cx.evaluateString(scope, "function f(x,y){ return x+y}", "<cmd>", 1, null); 
     try { 
      String result = (String) cx.evaluateString(scope, "f.toString()", "<cmd>", 1, null); 
      System.out.println(result); 
     } catch (org.mozilla.javascript.EcmaError ex) { 
      System.out.println(ex.getMessage()); 
     } 
    } 
} 
// Maven dependency 
// <dependency> 
//  <groupId>org.mozilla</groupId> 
//  <artifactId>rhino</artifactId> 
//  <version>1.7R4</version> 
// </dependency> 

輸出是:

function f(x, y) { 
    return x + y; 
}