Extracting source code of user defined methods from java file
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.
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.
Have you found an answer??
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?