一種獲取java代碼結構的實現思路
有時,我們需要獲取java文件里的代碼結構,即,只需要里面的class定義、方法聲明、屬性定義。不需要額外的方法實現
這里提供一下實現思路:
- 采用語法解析器Tree-sitter對java代碼進行解析,獲取里面的方法實現
- 遍歷第一步獲取到的方法列表,在源代碼中將方法replace為空字符串后,即為一個類的結構
備注:有關Tree-sitter,可參考官網介紹:
https://tree-sitter.github.io/tree-sitter/
獲取class中的import包、整個方法定義、方法中的代碼塊、塊狀注釋,部分代碼實現如下:
from code_ast.parsers import ASTParserclass MyASTParser(ASTParser):def __init__(self, lang):super().__init__(lang