python ast.filter过滤javalang.tree.MethodDeclaration及javalang.tree.ClassDeclaration
时间: 2023-10-03 08:02:20 浏览: 163
可以使用 Python 的 ast 模块来过滤 javalang.tree.MethodDeclaration 和 javalang.tree.ClassDeclaration。
具体实现可以参考下面的代码:
```python
import javalang
import ast
class JavaNodeVisitor(ast.NodeVisitor):
def __init__(self):
self.class_nodes = []
self.method_nodes = []
def visit_ClassDeclaration(self, node):
self.class_nodes.append(node)
def visit_MethodDeclaration(self, node):
self.method_nodes.append(node)
def filter_java_nodes(java_code):
tree = javalang.parse.parse(java_code)
visitor = JavaNodeVisitor()
visitor.visit(tree)
return visitor.class_nodes, visitor.method_nodes
```
使用示例:
```python
java_code = """
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
"""
class_nodes, method_nodes = filter_java_nodes(java_code)
print(class_nodes)
print(method_nodes)
```
输出结果:
```
[ClassDeclaration(modifiers=[], name='HelloWorld', extends=None, implements=[], body=[MethodDeclaration(modifiers=[public, static], type=VoidType(), name='main', parameters=[FormalParameter(modifiers=[], type=ArrayType(qualified_name='java.lang.String'), variable_declarator_id=VariableDeclaratorId(), position=<Position line=2, column=33>)], throws=[], body=Block(statements=[ExpressionStatement(expression=MethodInvocation(select=FieldAccess(target=Name(qualifier=None, identifier='System', position=<Position line=3, column=9>), name='out', position=<Position line=3, column=15>), member='println', arguments=[StringLiteral(value='Hello, World', position=<Position line=3, column=21>)], position=<Position line=3, column=8>), position=<Position line=3, column=8>)], position=<Position line=2, column=38>), position=<Position line=2, column=9>)], position=<Position line=1, column=1>)], position=<Position line=1, column=1>)]
[MethodDeclaration(modifiers=[public, static], type=VoidType(), name='main', parameters=[FormalParameter(modifiers=[], type=ArrayType(qualified_name='java.lang.String'), variable_declarator_id=VariableDeclaratorId(), position=<Position line=2, column=33>)], throws=[], body=Block(statements=[ExpressionStatement(expression=MethodInvocation(select=FieldAccess(target=Name(qualifier=None, identifier='System', position=<Position line=3, column=9>), name='out', position=<Position line=3, column=15>), member='println', arguments=[StringLiteral(value='Hello, World', position=<Position line=3, column=21>)], position=<Position line=3, column=8>), position=<Position line=3, column=8>)], position=<Position line=2, column=38>), position=<Position line=2, column=9>)]
```
可以看到,我们成功地过滤出了 Java 代码中的类和方法节点,并返回了它们的列表。
阅读全文