gpt4 book ai didi

Java:如何使用JavaParser获取Java类的标识符数量

转载 作者:行者123 更新时间:2023-12-01 19:54:06 24 4
gpt4 key购买 nike

我想使用JavaParser来获取java类拥有的标识符的数量。

我下载了JavaParser jar文件并将其添加到我的项目中,然后,我遵循了一些these指令,现在我能够以编程方式解析一些 Java 类并使用 ClassOrInterfaceDeclaration 中的方法,例如 .getMethods().getMembers() 等...

现在,我想知道如何获取每个类中标识符的数量。没有 .getIdentifiers() 方法,那么我应该采取什么方法?

最佳答案

如果您阅读 javadoc javaparser-core ,你会发现 JavaParser.parse(...) 返回 CompilationUnit ,这是 Node 在 AST(抽象语法树)中。

AST 可以被遍历,例如使用 walk(Consumer<Node> consumer) .

这是一个将遍历 source previously posted in a comment 的 AST 的程序,并打印所有节点。它将打印节点的标识符,如果有的话:

import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.nodeTypes.NodeWithIdentifier;

public class Test {
public static void main(String[] args) throws Exception {
String javaSource = "class MyClass {" +
" void main(String[] args) {" +
" int a = 5, b = 6;" +
" int c = a * b;" +
" System.out.println(c);" +
" }" +
"}";

System.out.printf("%-28s %-12s %s%n", "Node.class.simpleName", "Identifier", "Node.toString()");
System.out.printf("%-28s %-12s %s%n", "=====================", "==========", "===============");
JavaParser.parse(javaSource).walk(node -> {
String identifier = "";
if (node instanceof NodeWithIdentifier)
identifier = ((NodeWithIdentifier<?>) node).getIdentifier();
System.out.printf("%-28s %-12s %s%n",
node.getClass().getSimpleName(),
identifier,
node.toString().replaceFirst("(?s)\\R.*", "..."));
});
}
}

输出

Node.class.simpleName        Identifier   Node.toString()
===================== ========== ===============
CompilationUnit class MyClass {...
ClassOrInterfaceDeclaration class MyClass {...
SimpleName MyClass MyClass
MethodDeclaration void main(String[] args) {...
SimpleName main main
Parameter String[] args
ArrayType String[]
ClassOrInterfaceType String
SimpleName String String
SimpleName args args
VoidType void
BlockStmt {...
ExpressionStmt int a = 5, b = 6;
VariableDeclarationExpr int a = 5, b = 6
VariableDeclarator a = 5
PrimitiveType int
SimpleName a a
IntegerLiteralExpr 5
VariableDeclarator b = 6
PrimitiveType int
SimpleName b b
IntegerLiteralExpr 6
ExpressionStmt int c = a * b;
VariableDeclarationExpr int c = a * b
VariableDeclarator c = a * b
PrimitiveType int
SimpleName c c
BinaryExpr a * b
NameExpr a
SimpleName a a
NameExpr b
SimpleName b b
ExpressionStmt System.out.println(c);
MethodCallExpr System.out.println(c)
FieldAccessExpr System.out
NameExpr System
SimpleName System System
SimpleName out out
SimpleName println println
NameExpr c
SimpleName c c

关于Java:如何使用JavaParser获取Java类的标识符数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50191760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com