-
Notifications
You must be signed in to change notification settings - Fork 159
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Is there a way to print a node to string? #45
Comments
If I understand correctly you need to retrieve the name of the method being declared. In that case check the attributes:
|
No. I meant the entire code of a method in string. For example, javaparser even supports two types: one that pretty prints the code and one that preserves the original spaces. |
Thanks for the response :-) |
This is very old but this is the solution I came up with for my problem. def get_code_snippet (lines, index):
openingBrackets = 0;
closingBrackets = 0;
# Resulting snippet
snippet = ""
# loop until we find the final closing bracket, or go over the limit
while index < len(lines):
line = lines[index]
for letter in line:
if letter == '}':
closingBrackets += 1
elif letter == '{':
openingBrackets += 1
snippet += letter
# Early end if we have reached last bracket
if closingBrackets == openingBrackets and openingBrackets != 0:
return snippet
index += 1
return snippet I called the method in this way: lines = code.split("\n")
for child in node.body:
get_code_snippet (lines, child.position[0] - 1) I hope it can help anyone who stumbles upon this! |
Is there a way to convert a node (e.g.
MethodDeclaration
) into a string, either pretty-print (aka, reformatting) or print the original code?I didn't find such methods in javalang. I had experiences with Roslyn in .net and javaparse. Both support this functionality.
The text was updated successfully, but these errors were encountered: