Java Eclipse访客不离开测试文件的Main()

时间:2018-01-04 06:36:00

标签: java eclipse abstract-syntax-tree visitor

我正在尝试使用Eclipse AST包收集Java文件中的所有方法。我相信我已成功创建了CompilationUnit。但是,当我尝试使用访问者收集信息时,它不会超过我正在测试的文件的main()方法。

public void parseCode(String fileName) {
    String strSource = "";
    try {
        strSource = codeToString(fileName);
    } catch (Exception e) {
        e.printStackTrace();
    }
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(strSource.toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);

    final CompilationUnit cu = (CompilationUnit) parser.createAST(new NullProgressMonitor());

    SCTVisitor v = new SCTVisitor();
    cu.accept(v);
    System.out.println(v.m);
}

public class SCTVisitor extends ASTVisitor{
    List<SimpleName> m = new ArrayList<SimpleName>();

    SCTVisitor(){
        System.out.println("What is love");
    }

    @Override public boolean visit(MethodInvocation node) {
        this.m.add(node.getName());
        return true;
    }
}

这是我用来测试的文件的一部分:

import java.util.Map;
import java.util.Scanner;

import javax.swing.JFileChooser;
import javax.swing.UIManager;

public class WordCount {

public static void main(String[] args) {
System.out.println("Cheese");
    countWordsViaGUI();
}


// allow user to pick file to exam via GUI.
// allow multiple picks
public static void countWordsViaGUI() {
    setLookAndFeel();
    try {
        Scanner key = new Scanner(System.in);
        do {
            System.out.println("Opening GUI to choose file.");
            Scanner fileScanner = new Scanner(getFile());
            Stopwatch st = new Stopwatch();
            st.start();
            ArrayList<String> words = countWordsWithArrayList(fileScanner);
            st.stop();
            System.out.println("time to count: " + st);
            System.out.print("Enter number of words to display: ");
            int numWordsToShow = Integer.parseInt(key.nextLine());
            showWords(words, numWordsToShow);
            fileScanner.close();
            System.out.print("Perform another count? ");
        } while(key.nextLine().toLowerCase().charAt(0) == 'y');
        key.close();
    }
    catch(FileNotFoundException e) {
        System.out.println("Problem reading the data file. Exiting the program." + e);
    }
}

我的结果是:

[println, countWordsViaGUI]

我的预期结果是:

 [println, countWordsViaGUI, setLookAndFeel, scanner, println, getFile, Scanner, ...]

如果您对这个问题有任何了解,请告诉我。

0 个答案:

没有答案