我想只获得类级变量声明。如何使用javaparser获取声明?
public class Login {
private Keyword browser;
private String pageTitle = "Login";
}
使用javaparser必须获取变量"浏览器"的详细信息。喜欢浏览器的类型是" KeyWord"
答案 0 :(得分:5)
我不太清楚我理解你的问题 - 你想要获得班级的所有现场成员吗?如果是这样,你可以这样做:
CompilationUnit cu = JavaParser.parse(javaFile);
for (TypeDeclaration typeDec : cu.getTypes()) {
List<BodyDeclaration> 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());
}
}
}
此代码示例将在您的案例中打印: 关键词 浏览器 串 页面标题 “登录”
我希望这真的是你的问题......如果没有,请发表评论。
答案 1 :(得分:2)
更新上述JavaParser最新版本的答案:
handleSubmit
并且在没有太多麻烦的情况下获得现场声明的方法是......
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()));
}
});
}
}
两者之间的功能差异在于,第一个只查看顶级类,第二个也查看嵌套类。