获取 MethodDeclaration 的行号

get line number of a MethodDeclaration

我正在尝试创建 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;
    }
});

假设我们正在解析以下内容 class

public class Main
{
  /**
   *
   */
  public Main() {

  }
}

代码

cu.getLineNumber(node.getStartPosition())

而不是返回 6, returns 3. 显然 eclipse.jdt API 认为 javacode 也属于该方法。所以,我的问题是,如何获得方法 Main() 的 正确 行号?

EDIT_1

我们可以访问 Java文档:

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 class 的 toString 方法会忽略空行并将标签@param 视为两行,等等

干杯;)

调用MethodDeclarationgetName()获取方法名的ASTNode并获取该名称的行号

示例代码,希望对您有所帮助。

    public MethodNode getMethodforGivenLineNum(String srcFilePath, int linenum) {
        ASTParser parser = ASTParser.newParser(AST.JLS8);

        char[] fileContent = null;
        try {
            fileContent = getFileContent(srcFilePath).toCharArray();
        } catch (IOException e) {
            System.out.printf("getMethodforGivenLineNum-getFileContent failed!\n%s", srcFilePath);
            e.printStackTrace();
            return null;
        }

        parser.setSource(fileContent);

        CompilationUnit cu = (CompilationUnit) parser.createAST(null);

        List<MethodNode> methodNodeList = new ArrayList<>();

        cu.accept(new ASTVisitor() {
            @Override
            public boolean visit(MethodDeclaration node) {
                SimpleName methodName = node.getName();

                int startLineNum = cu.getLineNumber(node.getStartPosition());

                int endLineNum = cu.getLineNumber(node.getStartPosition() + node.getLength());

                methodNodeList.add(new MethodNode(methodName.toString(), node, startLineNum, endLineNum));
                return false;
            }
        });