例如,我可以获得开始行和结束行,但是如何获取开始行和结束行之间的源代码。 此处的示例代码。
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";
}
答案 0 :(得分:0)
您可以创建访问者类,例如
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();
}