Get variables from javascript expression (Rhino)

不打扰是莪最后的温柔 提交于 2019-12-05 17:58:11

Rhino 1.7 R3 introduced an AST package which can be used to find names:

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

Output:

[V1ND, abs, Math]

However, I'm not sure this will help much with efficiency unless the expressions are amenable to caching. You would be parsing the code twice and if you need to disambiguate a variable abs from the function on Math further inspection will be required.

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