java - 获取变量声明

标签 java eclipse-plugin

我为编译单元创建了一个 ASTParser 类型的解析器。我想使用此解析器列出此特定编译单元中存在的函数中的所有变量声明。我应该使用 ASTVisitor 吗?如果是这样怎么办或者还有其他办法吗?帮助

最佳答案

您可以尝试关注this thread

你应该看看org.eclipse.jdt.core插件,特别是ASTParser在那里上课。
只需启动解析器,以下代码就足够了:

ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT); // you tell parser, that source is whole java file. parser can also process single statements
parser.setSource(source);
CompilationUnit cu = (CompilationUnit) parser.createAST(null); // CompilationUnit here is of type org.eclipse.jdt.core.dom.CompilationUnit  
// source is either char array, like this:

public class A { int i = 9; int j; }".toCharArray()

//org.eclipse.jdt.core.ICompilationUnit type, which represents java source files

在工作区中。

after the AST is built, you can traverse it with visitor, that extends ASTVisitor, like this:

cu.accept(new ASTVisitor() {
  public boolean visit(SimpleName node) {
    System.out.println(node); // print all simple names in compilation unit. in our example it would be A, i, j (class name, and then variables)
    return true;
  }
});

更多详细信息和代码示例位于 this thread

ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(compilationUnit);
parser.setSourceRange(method.getSourceRange().getOffset(), method.getSourceRange().getLength());
parser.setResolveBindings(true);
CompilationUnit cu = (CompilationUnit)parser.createAST(null);
cu.accept(new ASTMethodVisitor());

关于java - 获取变量声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2324642/

相关文章:

java - Google App Engine - 在 java 中执行 php 的方法?

java - 在 Eclipse 4.2 中验证 XML 和 XSD - 缺少选项?

java - android中有字典数据类型吗?

java - 将具有依赖项的 Java 库打包到 OSGi/Eclipse jar 中

java - JTextField 的 Action 监听器更改另一个文本字段中的值

java - 安卓安装程序

java - eclipse 插件 - 像处理 java 文件一样处理非 java 扩展文件

java - Eclipse 扩展点与手动编程访问

java - 如何在我的 Java GUI 中使用 linkedList 和多个类

java - 服务器证书哈希码在 Java 版本之间发生变化