java - 如何在 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";
}
解决方案
您可以创建一个访问者类,例如
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();
}
推荐阅读
- arguments - 我们如何使用参数启动机器人远程服务器库?
- javascript - 使用锚标记打开模式时页面重定向到空白链接
- node.js - 为什么我的 Node.js express Server 不能在其他设备上运行?
- angular-cli - 安装 Angular Cli 时出现问题
- python - 命令 screen.fill() 不会重置屏幕上的对象
- php - 如何使用 Laravel Faker 在最小和最大字符数之间生成随机字符串
- php - Laravel - 总搜索帖子价格
- jquery - 如何在“dp.change”事件后使用选定的日期?
- go - 如何将 io.Reader 拆分为具有相同行数的多个 io.Reader?
- c++ - 从函数中正确传播 `decltype(auto)` 变量