java - 如何使用 javaparser 获取类级变量名?
问题描述
我能够使用以下代码获取类级别变量的声明。但我只需要变量名。这是我为以下代码得到的输出 - [private boolean flag = true;]
import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import java.io.FileInputStream;
public class CuPrinter{
public static void main(String[] args) throws Exception {
// creates an input stream for the file to be parsed
FileInputStream in = new FileInputStream("C:\\Users\\arosh\\IdeaProjects\\Bot_Twitter\\src\\MyBot.java");
CompilationUnit cu;
try {
// parse the file
cu = JavaParser.parse(in);
} finally {
in.close();
}
cu.accept(new ClassVisitor(), null);
}
private static class ClassVisitor extends VoidVisitorAdapter<Void> {
@Override
public void visit(ClassOrInterfaceDeclaration n, Void arg) {
/* here you can access the attributes of the method.
this method will be called for all methods in this
CompilationUnit, including inner class methods */
System.out.println(n.getFields());
super.visit(n, arg);
}
}
}
解决方案
您可以使用以下简单的正则表达式:
final String regex = "^((private|public|protected)?\\s+)?.*\\s+(\\w+);$";
然后可以编译成Pattern
:
final Pattern pattern = Pattern.compile(regex);
然后最后在 a 中使用for-loop
:
for(final String field : n.getFields()){
// create a regex-matcher
final Matcher matcher = pattern.matcher(field);
// if field matches regex
if(matcher.matches()){
// get the last group -> the fieldName
final String name = matcher.group(matcher.groupCount());
System.out.println("FieldName: " + name);
}
}
推荐阅读
- javascript - 在javascript中将此3d数组转换为2d数组
- javascript - React - history.push 重定向不起作用
- python - 在python中附加到一个空的JSON文件中
- c - 为什么 C 程序(删除一行)会删除我的 .txt 文件的第一个字符?
- django - 如何显示存储在 Django 会话系统中的本地 url 的缩略图?
- javascript - 我该如何解决:“渲染没有返回任何内容。这通常意味着缺少返回语句。或者,不渲染任何内容,返回 null。”
- node.js - 为作为 systemd 服务运行的 Nodejs 应用程序设置日志优先级
- azure - AzCopy 身份验证
- webpack - 为什么我的 Webpack5 配置不能在生产模式下使用文件系统缓存?
- amazon-cognito - IDP的COGNITO OIDC注销-OKTA