如何使用javaparser获取类级变量名?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何使用javaparser获取类级变量名?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1577字,纯文字阅读大概需要3分钟。
内容图文
我能够使用以下代码获取类级变量的声明.但我只需要变量名称.这是我得到以下代码的输出 – [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+);$";
然后可以编译成模式:
final Pattern pattern = Pattern.compile(regex);
然后最终用于for循环:
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);
}
}
内容总结
以上是互联网集市为您收集整理的如何使用javaparser获取类级变量名?全部内容,希望文章能够帮你解决如何使用javaparser获取类级变量名?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。