我正在尝试创建 Java 文件的解析器,但无法获取每个方法的正确行号。这是我现在的代码:
ASTParser parser = ASTParser.newParser(AST.JLS4);
parser.setSource(FileUtils.readFileToString(new File("Main.java"), "UTF-8").toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setResolveBindings(true);
Map options = JavaCore.getOptions();
JavaCore.setComplianceOptions(JavaCore.VERSION_1_5, options);
parser.setCompilerOptions(options);
final CompilationUnit cu = (CompilationUnit) parser.createAST(null /* IProgressMonitor */);
cu.accept(new ASTVisitor() {
public boolean visit(MethodDeclaration node) {
System.out.println("MethodName: " + node.getName().toString());
System.out.println("MethodLineNumber: " + cu.getLineNumber(node.getStartPosition()));
return false;
}
});
假设我们正在解析以下类
public class Main
{
/**
*
*/
public Main() {
}
}
代码
cu.getLineNumber(node.getStartPosition())
返回 3,而不是返回 6。显然 eclipse.jdt API 认为 javacode 也属于该方法。所以,我的问题是,如何获取方法 Main() 的正确行号?
EDIT_1
我们可以访问 JavaDoc:
String javadoc = node.getJavadoc().toString();
并计算行数
Pattern NLINE = Pattern.compile("(\n)|(\r)|(\r\n)");
Matcher m = NLINE.matcher(javadoc);
int lines = 1;
while (m.find())
lines++;
实际上适用于这种情况,但不适用于所有情况,例如
public class Main
{
/**
*
*
*
*
*
*
*
*/
public Main() {
}
}
-
node.getJavadoc().toString():
/**
*/
<小时/>
public class Main
{
/**
* Constructor
*
* @param <K> the key type
* @param <V> the value type
*/
public Main() {
}
}
-
node.getJavadoc().toString():
/**
* Constructor
* @param<K>
* the key type
* @param<V>
* the value type
*/
显然,Javadoc类的toString方法会忽略空行并将标签@param视为两行,等等
干杯;)
最佳答案
调用MethodDeclaration
的getName()
获取方法名称的ASTNode
,并获取该名称的行号。
关于java - 获取 MethodDeclaration 的行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28400127/