首页 > 解决方案 > 如何在 javaparser 中使用 getRange 获取源代码

问题描述

例如,我可以获取开始行和结束行,但是如何获取开始行和结束行之间的源代码。对于此处的示例代码。

String[] cmds =new String[2];
String OS = System.getProperty("os.name");
if (OS.startsWith("Windows")) {
    cmds[0]="cmd";
    cmds[1]="/c";
}
else {
    cmds[0]="/bin/sh";
    cmds[1]="-c";
}

try {
    Process p = Runtime.getRuntime().exec(cmds);
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

我想得到下面的代码,就是与cmds相关的定义。

String[] cmds =new String[2];
String OS = System.getProperty("os.name");
if (OS.startsWith("Windows")) {
     cmds[0]="cmd";
     cmds[1]="/c";
}
else {
     cmds[0]="/bin/sh";
     cmds[1]="-c";
}

标签: javajavaparser

解决方案


您可以创建一个访问者类,例如

 public class RangeFinder extends VoidVisitorWithDefaults<Range> {
    List<Node> nodesFound = new ArrayList<>();


    public void defaultAction(Node n, Range givenRange) {
        //Range of element in your code
        Range rangeOfNode = n.getRange().get();

        //If your given two lines contain this node, add it 
        if (givenRange.contains(rangeOfNode))
            nodesFound.add(n);
        //Else, if it overlaps with the node, check the children of the node
        else if (givenRange.overlapsWith(rangeOfNode)) {
            n.getChildNodes().forEach(child -> child.accept(this, givenRange));
        }
    }
}

然后使用方法

 public static String findSrc(CompilationUnit cu, int beginRow, int endRow) {
      //Parse code for all nodes contained within two rows
      RangeFinder rangeFinder = new RangeFinder();
      cu.accept(rangeFinder, Range.range(beginRow, 0, endRow, 0));

      //Build string
      StringBuilder codeBuilder = new StringBuilder();
      rangeFinder.nodesFound.forEach(node -> codeBuilder.append(node.toString()).append("\n"));
      return codeBuilder.toString();

}

推荐阅读