javalang
javalang copied to clipboard
Extracting full method declarations and fieldnames
All the previous question ask to extract method + its body as a text.
I want to know given a .java source, how can I extract method declarations which means:
- Modifiers
- Return type
- Function name
- Function arguments/parameters
as a python list.
PS: I don't need method's body.
Can the same be done for fields in class as well?
Is it possible with javalang?
Yes, it's possible, but you'll have to do some work yourself to make the list the way you want it.
- list all methods with
tree.filter(javalang.tree.MethodDeclaration) - for each method, its function name is
namefield - modifier is
modifiers - arguments: they will be listed in
parametersfield. Then, you need to retrieve the type and name of the parameter. - return value is
return_typefield. Get the type name withname.
This is an example of very simple method:
MethodDeclaration(annotations=[], body=[ReturnStatement(expression=This(postfix_operators=[], prefix_operators=[], qualifier=None, selectors=[MemberReference(member=msg, postfix_operators=None, prefix_operators=None, qualifier=None, selectors=None)]), label=None)], documentation=None, modifiers={'public'}, name=getMessage, parameters=[], return_type=ReferenceType(arguments=None, dimensions=[], name=String, sub_type=None), throws=None, type_parameters=None)
how can I get the body from this ? I tried the following code, but nothing works:
for path, node in tree.filter(javalang.tree.MethodDeclaration):
print(node['body'])
for path, node in tree.filter(javalang.tree.MethodDeclaration):
print(node[1])
EDIT: I am able to access it using node.body