In a Java Project of mine, I would like to find out programmatically which classes from a given API are used. Is there a good way to do that? Through source code parsing or
Something like this perhaps:
import java.io.*;
import java.util.Scanner;
import java.util.regex.Pattern;
public class FileTraverser {
public static void main(String[] args) {
visitAllDirsAndFiles(new File("source_directory"));
}
public static void visitAllDirsAndFiles(File root) {
if (root.isDirectory())
for (String child : root.list())
visitAllDirsAndFiles(new File(root, child));
process(root);
}
private static void process(File f) {
Pattern p = Pattern.compile("(?=\\p{javaWhitespace}*)import (.*);");
if (f.isFile() && f.getName().endsWith(".java")) {
try {
Scanner s = new Scanner(f);
String cls = "";
while (null != (cls = s.findWithinHorizon(p, 0)))
System.out.println(cls);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
You may want to take comments into account, but it shouldn't be too hard. You could also make sure you only look for imports before the class declaration.