如何使用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差异在于,第一个只查看顶级类,第二个也查看嵌套类。
- 在java Web应用程序中存储数据库字符串连接的位置?
- 可以使用lambda来就地更改List的值(不创建新列表)吗?
- 如何在Spring Boot中管理无限进程?
- 从S3下载文件> 3Gb失败,出现“SocketTimeoutException:Read timed out”
- 编写自定义Lombok Annotation处理程序
- 在没有ImageObserver的情况下在Java中获取图像的高度和宽度
- 需要示例Java代码来运行一个shellcript
- java.lang.ClassCastException:java.lang.Long无法在java 1.6中强制转换为java.lang.Integer
- 将辉光添加到基本Java矩形