java - 获取 MethodDeclaration 的行号

标签 java eclipse eclipse-jdt

我正在尝试创建 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视为两行,等等

干杯;)

最佳答案

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

关于java - 获取 MethodDeclaration 的行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28400127/

相关文章:

Eclipse 导入项目错误,工作区位置重叠

eclipse - 在 Eclipse 中以编程方式折叠

java - Eclipse JDT 编译器 (ECJ) 在 Java 1.7 中抛出 NPE

Java Swing 安排 JInternalFrames

java - 单线程应用程序中的 ArrayList 与 Vector 性能

java - 未应用elasticsearch jvm配置

java - Eclipse - Java 数组 ID 值相等。无法独立更改值

css - Eclipse:忽略 "Undefined CSS class"警告

eclipse - 以编程方式从 Eclipse 插件添加源文件夹

java - DataflowRunner 需要 gcpTempLocation,但无法从 PipelineOptions 检索值