2012-02-03 37 views
0

我創建了一個小程序,它讀入一個Java文件並將其從Eclipse JDT中提供給ASTParser以構建一個抽象語法樹(AST)。根節點是我能夠訪問的CompilationUnit。然後,我遍歷包含Java文件中的類的類型集合。就我而言,只有一個(公開課)。這個類被表示爲類型類型聲明的對象。我知道我已經成功地訪問了這個對象,因爲我能夠獲得它的SimpleName並將其打印到控制檯。爲什麼我的AST 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

回答

0

上述代碼的問題是換行符(\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個方法!

相關問題