2012-08-24 44 views
4

我使用Rhino來評估js表達式,將所有可能的變量值放在範圍中並評估一個匿名函數。然而,表達式非常簡單,我只想將表達式中使用的值用於表現。從javascript表達式獲取變量(Rhino)

代碼示例:

Context cx = Context.enter(); 

    Scriptable scope = cx.initStandardObjects(null); 

    // Build javascript anonymous function 
    String script = "(function() {" ; 

    for (String key : values.keySet()) { 
     ScriptableObject.putProperty(scope, key, values.get(key)); 
    } 
    script += "return " + expression + ";})();"; 

    Object result = cx.evaluateString(scope, script, "<cmd>", 1, null); 

我想所有這一切都是變量名的表達式令牌。

例如,如果表達的是

(V1ND < 0 ? Math.abs(V1ND) : 0) 

它將返回V1ND

+1

相關問題:[獲取函數名稱和他們的參數從評估JS與犀牛](http://stackoverflow.com/questions/11515710) – McDowell

回答

4

Rhino 1.7 R3推出了AST package可用於查找名稱:

import java.util.*; 
import org.mozilla.javascript.Parser; 
import org.mozilla.javascript.ast.*; 

public class VarFinder { 
    public static void main(String[] args) throws IOException { 
    final Set<String> names = new HashSet<String>(); 
    class Visitor implements NodeVisitor { 
     @Override public boolean visit(AstNode node) { 
     if (node instanceof Name) { 
      names.add(node.getString()); 
     } 
     return true; 
     } 
    } 
    String script = "(V1ND < 0 ? Math.abs(V1ND) : 0)"; 
    AstNode node = new Parser().parse(script, "<cmd>", 1); 
    node.visit(new Visitor()); 
    System.out.println(names); 
    } 
} 

輸出:

[V1ND, abs, Math] 

但是,我不知道這會幫助多少與效率,除非表達式是適合緩存。您將解析代碼兩次,如果您需要從Math上的函數中消除變量abs的歧義,則需要進一步檢查。

+0

我解決了它去年夏天在Runcc庫的幫助下(一個簡化的JS語法)。但是你的解決方案看起來很棒,我將用它來進行未來的重構。 –

+0

我做了重構並完美工作,謝謝! –