一种获取java代码结构的实现思路

一种获取java代码结构的实现思路

有时,我们需要获取java文件里的代码结构,即,只需要里面的class定义、方法声明、属性定义。不需要额外的方法实现

这里提供一下实现思路:

  1. 采用语法解析器Tree-sitter对java代码进行解析,获取里面的方法实现
  2. 遍历第一步获取到的方法列表,在源代码中将方法replace为空字符串后,即为一个类的结构

备注:有关Tree-sitter,可参考官网介绍:
https://tree-sitter.github.io/tree-sitter/

获取class中的import包、整个方法定义、方法中的代码块、块状注释,部分代码实现如下:

from code_ast.parsers import ASTParser

class MyASTParser(ASTParser):
    def __init__(self, lang):
        super().__init__(lang)

    def parse_edit(self, tree, editcode, keep_text = True):
        code_bytes = editcode.encode("utf-8")
        return self.parser.parse(code_bytes, tree, keep_text)


java_parse = MyASTParser("java")

root_tree, _ = java_parse.parse(target)

root_node = root_tree.root_node

def get_infos(node, method_blocks, methods, comments, includes, packages):
    if node:
        content = node.text.decode('utf-8')
        if node and node.type == "method_declaration":
            methods.append(content)
        if node and node.type == 'package_declaration':
            packages.append(content)
        if node and node.parent and node.type == 'block' and node.parent.type == "method_declaration":
            method_blocks.append(content)
        if node and node.parent and node.type == "block_comment" and node.parent.type == "program":
            comments.append(content)
        if node and node.type == "import_declaration":
            includes.append(content)
    for child in node.children:
        get_infos(child, method_blocks, methods, comments, includes, packages)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

行动π技术博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值