如何打印javalang.ast.Node中所有节点名称
时间: 2023-06-27 16:05:59 浏览: 109
要打印`javalang.ast.Node`中所有节点的名称,可以遍历AST并使用`getClass().getSimpleName()`方法获取节点类的简单名称。
以下是一个示例代码:
```java
import javalang.ast.*;
public class ASTPrinter {
public static void printNodeNames(Node node) {
System.out.println(node.getClass().getSimpleName());
for (Node child : node.getChildren()) {
printNodeNames(child);
}
}
public static void main(String[] args) {
// parse some Java code into an AST
String code = "public class HelloWorld {\n" +
" public static void main(String[] args) {\n" +
" System.out.println(\"Hello, world!\");\n" +
" }\n" +
"}";
CompilationUnit compilationUnit = StaticJavaParser.parse(code);
// print the names of all nodes in the AST
printNodeNames(compilationUnit);
}
}
```
该程序将输出以下内容:
```
CompilationUnit
PackageDeclaration
Name
SimpleName
ClassOrInterfaceDeclaration
SimpleName
MethodDeclaration
SimpleName
Parameter
ArrayType
SimpleName
BlockStmt
ExpressionStmt
MethodCallExpr
FieldAccessExpr
SimpleName
StringLiteralExpr
```
阅读全文