使用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源的所有变量的列表,无论范围如何。
答案 0 :(得分:8)
解决方案是创建一个扩展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());
}
}
答案 1 :(得分:2)
请注意,根据您的解决方案,可以使用以下代码完成原始字段列表:
@Override
public void visit(FieldDeclaration n, Object arg) {
System.out.println(n);
super.visit(n, arg);
}
如果要覆盖访问者适配器中的多个访问方法,请不要忘记调用super.visit。
答案 2 :(得分:1)
工作:
在visit(FieldDeclaration n, Object arg)
类的VoidVisitorAdapter
方法中,以下内容可用于提取变量。
它将给出变量的确切名称,无论是否已初始化。
String newstr;
List<VariableDeclarator> list = n.getVariables();
//as getVariables() returns a list we need to implement that way
for (VariableDeclarator var : list) {
String item = var.toString();
if (item.contains("=")) {
if (item != null && item.length() > 0) {
int index = item.lastIndexOf("=");
newstr = item.substring(0, index);
newstr = newstr.trim();
variablename = newstr;`
//variablename is the name of the desired variable.
}
}
}