javalang icon indicating copy to clipboard operation
javalang copied to clipboard

Extracting full method declarations and fieldnames

Open pjcuser opened this issue 3 years ago • 2 comments

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?

pjcuser avatar Sep 05 '22 04:09 pjcuser

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 name field
  • modifier is modifiers
  • arguments: they will be listed in parameters field. Then, you need to retrieve the type and name of the parameter.
  • return value is return_type field. Get the type name with name.

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)

cryptax avatar Sep 26 '22 16:09 cryptax

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

faysalhossain2007 avatar Oct 06 '22 18:10 faysalhossain2007