如何使用javaparser获取类级变量声明?

我想只获得类级变量声明。 如何使用javaparser获取声明?

public class Login { private Keyword browser; private String pageTitle = "Login"; } 

使用javaparser必须得到变量“浏览器”的详细信息,就像浏览器的类型是“KeyWord”

我不太清楚我理解你的问题 – 你想要获得class级的所有现场成员吗? 如果是这样你就可以这样做:

 CompilationUnit cu = JavaParser.parse(javaFile); for (TypeDeclaration typeDec : cu.getTypes()) { List members = typeDec.getMembers(); if(members != null) { for (BodyDeclaration member : members) { //Check just members that are FieldDeclarations FieldDeclaration field = (FieldDeclaration) member; //Print the field's class typr System.out.println(field.getType()); //Print the field's name System.out.println(field.getVariables().get(0).getId().getName()); //Print the field's init value, if not null Object initValue = field.getVariables().get(0).getInit(); if(initValue != null) { System.out.println(field.getVariables().get(0).getInit().toString()); } } } 

此代码示例将在您的情况下打印:关键字浏览器字符串pageTitle“登录”

我希望这真的是你的问题……如果没有,请发表评论。

要更新上述JavaParser最新版本的答案:

 CompilationUnit cu = JavaParser.parse("public class Login {\n" + "\n" + " private Keyword browser;\n" + " private String pageTitle = \"Login\";\n" + "}\n"); for (TypeDeclaration typeDec : cu.getTypes()) { for (BodyDeclaration member : typeDec.getMembers()) { member.toFieldDeclaration().ifPresent(field -> { for (VariableDeclarator variable : field.getVariables()) { //Print the field's class typr System.out.println(variable.getType()); //Print the field's name System.out.println(variable.getName()); //Print the field's init value, if not null variable.getInitializer().ifPresent(initValue -> System.out.println(initValue.toString())); } }); } } 

而没有那么多麻烦的方法来获得现场声明是…

 cu.findAll(FieldDeclaration.class).forEach(field -> { field.getVariables().forEach(variable -> { //Print the field's class typr System.out.println(variable.getType()); //Print the field's name System.out.println(variable.getName()); //Print the field's init value, if not null variable.getInitializer().ifPresent(initValue -> System.out.println(initValue.toString())); }); }); 

两者之间的function差异在于,第一个只查看顶级类,第二个也查看嵌套类。