我想在Java文件的所有方法中检索所有变量名。像Person.java包含的示例
class Person {
private String firstName;
private String lastName;
public static void main() {
String test = "test";
Person p1 = new Person();
p1.setName("John");
}
public void setName(String name) {
this.firstName = name;
}
}
我希望能够打印出所有声明的变量。我尝试使用javaparser检索它们。但是,我只能检索在类中声明的变量
firstName
lastName 我也希望能够检索在main方法中声明的所有变量
firstName lastName test 我的javaparser方法是
public static void getVariables(String inputFilePath) {
try {
CompilationUnit cu = StaticJavaParser.parse(new File(inputFilePath));
cu.findAll(FieldDeclaration.class).forEach(field -> {
field.getVariables().forEach(variable -> {
System.out.println(variable.getName());
variable.getInitializer().ifPresent(initValue ->
System.out.println(initValue.toString()));
});
});
} catch (FileNotFoundException fe) {
System.out.println(fe.getMessage());
} catch (IOException e){
System.out.println(e.getMessage());
}
}
解决了
按照Eugene的建议,我现在可以检索所有变量
public static void getVariables(String inputFilePath) {
try {
CompilationUnit cu = StaticJavaParser.parse(new File(inputFilePath));
cu.findAll(VariableDeclarator.class).forEach(variable -> {
System.out.println(variable);
});
} catch (FileNotFoundException fe) {
} catch (IOException e) {
}
}
问题来源:Stack Overflow
你传入FieldDeclaration.class到CompilationUnit的的findAll()方法。因此,按照要求,它将获取所有已声明的字段。
如果要列出所有声明的变量,请VariableDeclarator.class在同一包中使用–它会为您提供所有这些变量,包括声明为字段的变量。
回答来源:Stack Overflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。