gpt4 book ai didi

java - 使用 JavaParser 解析变量的正确方法是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:13:58 31 4
gpt4 key购买 nike

使用 JavaParser 我可以获得我的方法和字段的列表:

//List of all methods
System.out.println("Methods: " + this.toString());
List<TypeDeclaration> types = n.getTypes();
for (TypeDeclaration type : types)
{
List<BodyDeclaration> members = type.getMembers();
for (BodyDeclaration member : members)
{
if (member instanceof MethodDeclaration)
{
MethodDeclaration method = (MethodDeclaration) member;
System.out.println("Methods: " + method.getName());
}
}
}

//List all field variables.
System.out.println("Field Variables: " + this.toString());
List<TypeDeclaration> f_vars = n.getTypes();
for (TypeDeclaration type : f_vars)
{
List<BodyDeclaration> members = type.getMembers();
for (BodyDeclaration member : members)
{
if (member instanceof FieldDeclaration)
{
FieldDeclaration myType = (FieldDeclaration) member;
List <VariableDeclarator> myFields = myType.getVariables();
System.out.println("Fields: " + myType.getType() + ":" + myFields.toString());
}
}
}

但我不知道如何获取我的变量列表。我只是想要一个来自 java 源的所有变量的列表,而不考虑范围。

最佳答案

解决方案是创建一个扩展 VoidVisitorAdapter 并覆盖 visit() 方法的访问者类。代码如下:

@Override
public void visit(VariableDeclarationExpr n, Object arg)
{
List <VariableDeclarator> myVars = n.getVars();
for (VariableDeclarator vars: myVars){
System.out.println("Variable Name: "+vars.getId().getName());
}
}

关于java - 使用 JavaParser 解析变量的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13971424/

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