0

I'm not able to get a correct line of methods. Few are getting properly few are not.

for (CtMethod declaredMethod : declaredMethods) {
        int methodLineNumber = declaredMethod.getMethodInfo().getLineNumber(0);
}

1)What is the mistake?
2)In getLineNumber(int offset) how to calculate offset?

kumar
  • 11
  • 1
  • 2
    What line number are you trying to get? A method usually spans many lines. Are you trying to get the line which the method header is on? – Sweeper Apr 21 '20 at 12:44
  • Yes, Method declaration or starting of the method. – kumar Apr 21 '20 at 12:47
  • 1
    This information is not available. Only executable code is associated with line numbers in the debugging information. So you can only get the method’s first line resulting in executable code. For abstract and native methods, no line numbers are available at all. – Holger Apr 21 '20 at 13:55

1 Answers1

0

If I understood your question correctly, you are looking on finding out the associated starting line number of all methods in your java code

I would suggest you to use JavaParser (https://javaparser.org/)

Github Link - https://github.com/javaparser/javaparser

It is a java code analysis tool using which I too solved a problem on similar lines

You may need to override the visit method found in VoidVisitorAdapter

private static class MethodStartLine extends VoidVisitorAdapter {
    @Override
    public void visit(MethodDeclaration md, Object arg) {

        System.out.println("METHOD: " + md.getDeclarationAsString() + "STARTS AT" + md.getRange().get().begin.line);

    }
}

You need to set a Compilation Unit and pass it on as below in your driver code

private static void getMethodStartLineNumbers(File src) throws ParseException, IOException {
    CompilationUnit cu = JavaParser.parse(src);
    new MethodStartLine().visit(cu, null);
}

The File src here can be made using the Files.walk() if you need to run it on multiple files

File mySrc = new File(srcRoot, filePath)

where the filePath is the path to file on which you need your java parser to run which can be called with

getMethodStartLineNumbers(File mySrc)

PS: the EBook available on their website gives you great intro to Java Parsers

anon-sAI
  • 53
  • 1
  • 9