【问题标题】:Why is my AST TypeDeclaration missing its Methods and Fields?为什么我的 AST TypeDeclaration 缺少其方法和字段?
【发布时间】:2012-02-03 04:04:57
【问题描述】:

我创建了一个小程序,它读取 Java 文件并将其从 Eclipse JDT 提供给 ASTParser 以构建抽象语法树 (AST)。根节点是我可以访问的 CompilationUnit。然后,我遍历包含 Java 文件中的类的 Types 集合。就我而言,只有一个(公共类)。此类表示为 TypeDeclaration 类型的对象。我知道我已经成功访问​​了这个对象,因为我能够获取它的 SimpleName 并将其打印到控制台。

TypeDeclaration 有很多方法,包括getFields()getMethods()。但是,当我调用这些方法时,它们返回的集合是空的。我正在阅读的 Java 类当然同时具有字段和方法,所以我不明白为什么它会显示为空。任何想法是什么原因造成的?我是否以某种方式滥用了这个 API,或者我没有初始化一些东西?

这是我用于访问 AST 的代码的简化版本:

// char array to store the file in
char[] contents = null;
BufferedReader br = new BufferedReader(new FileReader(this.file));
StringBuffer sb = new StringBuffer();
String line = "";
while((line = br.readLine()) != null) {
    sb.append(line);
}
contents = new char[sb.length()];
sb.getChars(0, sb.length()-1, contents, 0);

// Create the ASTParser
ASTParser parser = ASTParser.newParser(AST.JLS4);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(contents);
parser.setResolveBindings(true);
CompilationUnit parse = (CompilationUnit) parser.createAST(null);

// look at each of the classes in the compilation unit
for(Object type : parse.types()) {
    TypeDeclaration td = (TypeDeclaration) type;
    // Print out the name of the td
    System.out.println(td.getName().toString()); // this works
    FieldDeclaration[] fds = td.getFields();
    MethodDeclaration[] mds = td.getMethods();
    System.out.println("Fields: " + fds.size()); // returns 0???
    System.out.println("Methods: " + mds.size()); // returns 0???
}

这是我正在阅读的 Java 文件:

public class Vector {

    // x, the first int value of this vector
    private int x;

    // y, the second int value of this vector
    private int y;

    public Vector(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public String toString() {
        return "Vector( " + this.x + " , " + this.y + " )";
    }

    public int getX() {
        return x;
}

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }
}

因此,正如预期的那样,我的 AST 代码中的第一个打印结果是 Vector,但随后的打印结果是 Fields: 0Methods: 0,而我实际上期望 Fields: 2Methods: 6

【问题讨论】:

    标签: java abstract-syntax-tree eclipse-jdt


    【解决方案1】:

    上述代码的问题是换行符(\n)丢失了。每次将 BufferedReader 的内容附加到 StringBuffer (sb) 时,都不会包含 \n。结果是,从示例程序的第 3 行开始,所有内容都被注释掉了,因为程序被读入如下:

    public class Vector { // x, the first int value of this vector private int x; ...
    

    不过不用担心,因为有一个简单的解决方案。在解析程序的 while 循环内,简单地将 \n 附加到读取的每一行输入的末尾。如下:

    ...
    while((line = br.readLine()) != null) {
        sb.append(line + "\n");
    }
    ...
    

    程序现在应该可以正确读入,并且输出应该是,如预期的那样,2 个字段和 6 个方法!

    【讨论】:

      猜你喜欢
      • 2020-10-26
      • 2021-05-23
      • 2014-02-17
      • 1970-01-01
      • 1970-01-01
      • 2022-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多