[英]How to get the source code using getRange in javaparser
例如,我可以獲取開始行和結束行,但是如何獲取開始行和結束行之間的源代碼。 對於此處的示例代碼。
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";
}
你可以創建一個訪客 class 像
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.