I’m trying to create a parser of Java files, but I can’t get the correct line number of each method. this is the code that I’ve right now:
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; } });
imagine that we’re parsing the following class
public class Main { /** * */ public Main() { } }
the code
cu.getLineNumber(node.getStartPosition())
instead of returning 6, returns 3. apparently the eclipse.jdt API considers that javacode also belongs to the method. so, my question is, how to get the correct line number of method Main()?
EDIT_1
we can have access to the JavaDoc:
String javadoc = node.getJavadoc().toString();
and count the number of lines
Pattern NLINE = Pattern.compile("(n)|(r)|(rn)"); Matcher m = NLINE.matcher(javadoc); int lines = 1; while (m.find()) lines++;
and in fact works for that case but not to all cases, like for example
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 */
apparently, toString method of Javadoc class ignores empty lines and considers label @param as two lines, etc.
Cheers 😉
Advertisement
Answer
Call the getName()
of MethodDeclaration
to get the ASTNode
for the method name and get the line number of the name.