如何从ASTParser打印所有方法声明和调用

时间:2014-05-10 03:23:09

标签: java abstract-syntax-tree

我想在Class的所有方法中打印所有方法调用。我正在使用ASTParser。以下是我的代码

import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import java .io.*;

public class ASTParserDemo {
public static void main(String[] args) {


    ASTParserDemo demo = new ASTParserDemo();
    String rawContent = demo.readFile();

    //String rawContent = "public class HelloWorld { public String s = \"hello\"; public static void main(String[] args) { HelloWorld hw = new HelloWorld(); String s1 = hw.s; } }";
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(rawContent.toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    AST ast = cu.getAST();
    IdentifierVisitor iv = new IdentifierVisitor();
    cu.accept(iv);

}

public String readFile() {
    StringBuffer fileContent = new StringBuffer();
    BufferedReader br = null;
    try {
        String sCurrentLine;
        br = new BufferedReader(new FileReader("C:\\research\\android-projects\\AsyncSearch.java"));

        while ((sCurrentLine = br.readLine()) != null) {
            //System.out.println(sCurrentLine);
            fileContent.append(sCurrentLine);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return fileContent.toString();
}

}

import org.eclipse.jdt.core.dom.*;

import java.util.*;

public class IdentifierVisitor extends ASTVisitor {

private Vector<String> identifiers = new Vector<String>();

public Vector<String> getIdentifiers(){
    return identifiers; 
}


public boolean visit(MethodDeclaration m){
    System.out.println("METHOD DECLARATION : " + m);
    return true;
}

public boolean visit(MethodInvocation m){
    System.out.println("METHOD INVOCATION : " + m);
    return true;
}

}

输出只显示一个方法声明。请让我知道如何在所有声明的方法中打印所有方法调用。感谢

1 个答案:

答案 0 :(得分:1)

您没有使用好方法来检索源代码的字符串表示形式。您可以使用替代方法从路径中读取文件并返回source:

的字符串表示形式
public static String readFileToString(String filePath) throws IOException {
    StringBuilder fileData = new StringBuilder(1000);
    BufferedReader reader = new BufferedReader(new FileReader(filePath));

    char[] buf = new char[10];
    int numRead = 0;
    while ((numRead = reader.read(buf)) != -1) {
        //          System.out.println(numRead);
        String readData = String.valueOf(buf, 0, numRead);
        fileData.append(readData);
        buf = new char[1024];
    }
    reader.close();
    return  fileData.toString();    
}

请记住在调用readFileToString(filePath)之前始终检查它是否是实际文件,例如:

String filePath = file.getAbsolutePath();
if (file.isFile ())) 
     String source = readFileToString(filePath) 

或者,您可以打印从方法readFile返回的rawContent的内容,并检查您要解析的代码实际上与您的意思相同。

相关问题