1 基本使用
相关demo
GitHub - c2nes/javalang: Pure Python Java parser and tools
迭代Node
for path, node in tree: print path, node
输出
() CompilationUnit (CompilationUnit,) PackageDeclaration (CompilationUnit, [ClassDeclaration]) ClassDeclaration
按类型过滤
这里过滤类相关声明ClassDeclaration,得到结果与上面(CompilationUnit, [ClassDeclaration]) ClassDeclaration 一致
也可以只获取node信息
>>> for path, node in tree.filter(javalang.tree.ClassDeclaration):
... print(node)
...
ClassDeclaration(annotations=[], body=[], documentation=None, extends=None, implements=None, modifiers=set(), name=Test, type_parameters=None)
然后从node信息中选择我们想要的,如node.name
>>> for path, node in tree.filter(javalang.tree.ClassDeclaration):
... print(node.name)
...
Test
2 查找符合条件的类
查询我们想查询的信息,如MethodDeclaration
for path, node in tree: if isinstance(node, MethodDeclaration): print(node)
方法调用:MethodInvocation
for path, node in tree: if isinstance(node, MethodInvocation): print(node)
传入ClassDeclaration.methods,查看里面的方法调用
def getfitmethods2(method_node):
# 判断是否是MethodDeclaration对象
if isinstance(method_node,MethodDeclaration):
print(method_node.name)
# 找方法调用
for path, node in method_node:
if isinstance(node, MethodInvocation):
print("-----"+node.member)
参考:
python 解析 java文件 --- javalang 模块_high_tea的博客-CSDN博客_python解析java文件python 的 javalang 库【2】_Attribute47的博客-CSDN博客
python 的 javalang 库【1】_Attribute47的博客-CSDN博客_python的javalang