javalang icon indicating copy to clipboard operation
javalang copied to clipboard

Extracting source code of user defined methods from java file

Open ghost opened this issue 6 years ago • 3 comments

Hi,

I would like to extract source code of user defined methods from a java file.

Suppose, we have a following code in a java file:

public class CallingMethodsInSameClass
{
     public static void main(String[] args) {
        printOne();
        printOne();
        printTwo();
      }

    public static void printOne() {
       System.out.println("Hello World");
     }

     public static void printTwo() {
       printOne();
       printOne();
    } 
}

The output should be:

Method 1:

public static void main(String[] args) {
        printOne();
        printOne();
        printTwo();
 }

Method 2:

public static void printOne() {
    System.out.println("Hello World");
 }

Method 3:

public static void printTwo() {
    printOne();
    printOne();
} 

Is there a way to do it by using javalang? Please let me know about it.

ghost avatar Dec 23 '19 08:12 ghost

I'm facing a similar question, all I need is to know the start and end line number of a method. I can know the start line by accessing the .position attribute of a MethodDeclaration node, but don't know where to find the endline. Another item in .position seems to be the column number of the declaration.

LeonYang95 avatar Jan 07 '20 07:01 LeonYang95

Have you found an answer??

anshul17024 avatar Jun 17 '20 16:06 anshul17024

all I need is to know the start and end line number of a method.

It is possible to traverse over all children and check the maximum code_line:

def find_start_and_end_lines(node, patterns_list):
    """Finds start and end line of a node.
    :return: start line, end line
    """
    max_line = node.position.line

    def traverse(node):
        for child in node.children:
            if isinstance(child, list) and (len(child) > 0):
                for item in child:
                    traverse(item)
            else:
                if hasattr(child, '_position'):
                    nonlocal max_line
                    if child._position.line > max_line:
                        max_line = child._position.line
                        return

    traverse(node)
    return node.position.line, max_line

@YangLin-George , Is that you need?

lyriccoder avatar Jul 07 '20 11:07 lyriccoder